我无法弄清楚我的代码是如何工作的,试图在/ blog /上显示post_detail.html,NoReverseMatch 反向' post_detail'参数'(2,)'和关键字参数' {}'未找到。尝试了1种模式:['博客/ $ post /(?P \ d +)/ $']
这是我的代码: 的 blog.views.py
def post_list(request):
posts =Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts':posts})
def post_detail(request, post_pk):
post = Post.objects.get(pk=post_pk)
return render(request, 'blog/post_detail.html', {'post': post})
blog.urls.py
app_name='blog'
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<post_pk>\d+)/$', views.post_detail, name='post_detail'),
]
urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/$', include(blog_urls, namespace='blog')),
]
post_list.html
{%extends&#39; blog / base.html&#39; %}
{%block content%}
{% for post in posts %}
< -- here is the error
<h1><a href="{% url 'blog:post_detail' post.pk %}">{{post.title}}</a></h1>
<p>published by: {{ post.published_date }}</p>
<p>{{post.author}}</p>
<p>{{post.text|linebreaksbr}}</p>
{% endfor %}
{%endblock%}
答案 0 :(得分:0)
从$
的网址中删除正则表达式字符串结尾符合字符include
:
url(r'^blog/', include(blog_urls, namespace='blog')),
# ^
这恰好是Django文档提到的预期错误:
请注意,此示例中的正则表达式没有
$
(字符串结尾匹配字符)但包含尾部斜杠。 每当Django遇到include()
(django.conf.urls.include()
)时, 它会切断匹配到该点的URL的任何部分 将剩余的字符串发送到包含的 URLconf 以进一步 处理