2017-07-16 144 views
0

我正在試圖在瀏覽器上運行與django的博客版本。而我得到這個錯誤:運行Django時,'Reverse'是什麼意思?

NoReverseMatch at/ 
Reverse for 'blog.views.post_detail' not found. 
'blog.views.post_detail' is not a valid view function or pattern name. 

url.py我的應用程序的樣子:

from django.conf.urls import include, url 
from . import views 

urlpatterns = [ 
    url(r'^$', views.post_list), 
    url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail), 
] 

看來,當我鍵入127.0.0.1:8000/
該網址將指向views.post_list
而我views.py樣子:

from django.shortcuts import render, get_object_or_404 
from .models import Post 

def post_list(request): 
    posts = Post.objects.filter(published_date__isnull=False) 
    return render(request, 'blog/post_list.html', {'posts': posts} 

def post_detail(request, pk): 
    post = get_object_or_404(Post, pk=pk) 
    return render(request, 'blog/post_detail.html', {'post': post}) 

post_list()將呈現與post_list.html請求。
裏面post_list.html,錯誤來自行:

<h1><a href="{% url 'blog.views.post_detail' pk=post.pk %}">{{ post.title }}</a></h1> 

我真的不明白「反向」是指在錯誤消息。 'blog.views.post_detail'確實存在於views.py。我想我得到了代碼所需的一切,但無法弄清楚哪裏出了問題。

我是新來的django,抱歉,如果問題是基本的,謝謝回答!

+0

也許看看[此帖](https://開頭stackoverflow.com/questions/43453368/noreversematch-at-product-pussyes-reverse-for-basket-adding-not-found-bask) – PRMoureu

+0

你在哪裏定義你想鏈接到的post_detail的URL? –

回答

0

Django 1.10刪除了通過視圖的虛線導入路徑反轉URL的功能。相反,你需要命名URL模式,並使用該名稱扭轉網址:

urlpatterns = [ 
    url(r'^$', views.post_list, name='post-list'), 
    url(r'^(?P<pk>\d+)/$', views.post_detail, name='post-detail'), 
] 

而且在你的模板:

<h1><a href="{% url 'post-detail' pk=post.pk %}">{{ post.title }}</a></h1> 
+0

它的工作原理,謝謝。但是,「逆向」是做什麼的? – Zhemy

+0

@Zhemy查看[反向解析網址](https://docs.djangoproject.com/en/1.11/topics/http/urls/#reverse-resolution-of-urls)。 'url'模板標籤調用'reverse()'。 – knbk

+0

Okey我看到了,非常感謝! – Zhemy

0

看來你的urls.py應該如下:

from django.conf.urls import include, url 
from . import views 

urlpatterns = [ 
    url(r'^$', views.post_list), 
    url(r'^(?P<pk>\d+)/$', views.post_detail), 
] 
+0

對不起,我的代碼中有第二行url(),但我認爲這裏並不重要,並且刪除它。 – Zhemy

0

你應該爲你的網址定義名稱:

urlpatterns [ 
    url(r'^$', views.post_list,name=post_list), 
] 

然後使用URL標記是這樣的:

<a href="{% url 'AppName:post_list' %}"></a> 

AppName是你的Django應用程序名稱。

+0

它說「'博客'不是已註冊的命名空間」,我可以在哪裏查看我的命名空間?名稱空間實際上代表了什麼? – Zhemy

+0

您是否在django設置文件中添加了您的應用程序INSTALLED_APPS = []? – pooya

+0

此外,您還必須將您的應用添加到您的djago項目的urls.py文件(而不是您的應用中的urls.py) – pooya