【问题标题】:NoReverse Match at "" Reverse for "" with arguments '()' and keyword arguments '{}'NoReverse 匹配 "" Reverse for "" 参数 '()' 和关键字参数 '{}'
【发布时间】:2014-10-03 01:51:46
【问题描述】:

我试图在 Django 中显示指向列表视图的链接列表,但我不断收到“NoReverse Match”错误。

模板

{% for posts in all_posts %}
<a href="{% url 'blog:blog_single' posts.slug %}">{{posts.title}}</a>
{% endfor %}

观看次数

from blog.models import Posts
from main_site.views import LayoutView

class BlogView(LayoutView, generic.ListView):
    template_name = 'blog/blog.html'
    model = Posts
    context_object_name = 'all_posts'

博客/网址

urlpatterns = patterns('',
    url(r'^(?P<slug>\w+)/$', views.SingleView.as_view(), name='blog_single'),
    url(r'^$', views.BlogView.as_view(), name='blog_home'),
)

项目/网址

urlpatterns = patterns('',
    url(r'^blog/', include('blog.urls', namespace='blog')),
)

slug 是我的模型中设置为 models.SlugField() 的属性,如果我输出为 {{posts.slug}} 它会显示出来,所以我知道它不是空的。我在项目的另一个应用程序中设置了一个类似的链接,它工作正常(完全相同的设置——url'namespace:name')所以我不确定是什么导致它中断。

完整的错误是:

NoReverseMatch at /blog/

Reverse for 'blog_single' with arguments '(u'test-slug',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'blog/(?P<slug>\\w+)/$']

【问题讨论】:

    标签: django django-templates django-urls


    【解决方案1】:

    这是因为您的网址格式错误。

    url(r'^(?P<slug>\w+)/$', views.SingleView.as_view(), name='blog_single'),
    

    期待 \w+ (即任何字母字符、数字字符或下划线)。但是您为它提供了一个包含破折号(“-”)的文本。

    因此,您需要将 slug 或 url 模式更改为:

    url(r'^(?P<slug>[\w-]+)/$', views.SingleView.as_view(), name='blog_single'),
    

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 1970-01-01
      • 2016-03-18
      • 2012-10-23
      • 2015-10-15
      • 2020-10-21
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多