【问题标题】:How to fix NoReverseMatch at/blog/ Django 1.8 Url如何在/blog/Django 1.8 Url 修复 NoReverseMatch
【发布时间】:2017-11-26 08:06:58
【问题描述】:

我无法弄清楚我的代码是如何工作的,试图在 /blog/ 上显示 post_detail.html、NoReverseMatch 未找到带有参数“(2,)”和关键字参数“{}”的“post_detail”的反向操作。尝试了 1 种模式:['blog/$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

{% 扩展 'blog/base.html' %}

{% 块内容 %}

{% 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%}

【问题讨论】:

    标签: python django


    【解决方案1】:

    include中的url中删除正则表达式字符串结尾匹配字符$

    url(r'^blog/', include(blog_urls, namespace='blog')),
    #           ^
    

    这恰好是 Django 文档中提到的预期错误:

    请注意,此示例中的正则表达式没有 $ (字符串结尾匹配字符),但包含尾部斜杠。 每当 Django 遇到include() (django.conf.urls.include()), 它会切断与该点匹配的 URL 的任何部分,并且 将剩余的字符串发送到包含的 URLconf 以进一步 处理。

    【讨论】:

    • 感谢您的帮助和信息先生,我已经挣扎了大约 3 个小时,
    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多