NoReverseMatch问题(Tango与Django 1.7 [10.5])

时间:2015-08-03 01:33:22

标签: python django

我正在教自己django,并遇到了一个错误,我无法解决自己的问题。我尝试过在类似问题的StackExchange答案中找到的一些建议,但没有成功。

问题:

我正在尝试使用url模板标记,如下所示:

的index.html

...
{% if categories %}
    <ul>
        {% for category in categories %}
        <li><a href="{% url 'rango:category' category.slug %}">{{ category.name }}</a></li>
        {% endfor %}
    </ul>
{% else %}
    <strong>There are no categories present.</strong>
{% endif %}
...

urls.py

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^about/$', views.about, name='about'),
    url(r'^add_category/$', views.add_category, name='add_category'),
    url(r'^category/(?P<category_name_slug>[\w]+)/$', views.category, name='category'),
    url(r'^category/(?P<category_name_slug>[\w]+)/add_page/$', views.add_page, name='add_page'),
    url(r'^register/$', views.register, name='register'),
    url(r'^login/$', views.user_login, name='login'),
    url(r'^restricted/$', views.restricted, name='restricted'),
    url(r'^logout/$', views.user_logout, name='logout'),
    )

views.py

def category(request, category_name_slug):

    context_dict = {}

    try:
        category = Category.objects.get(slug=category_name_slug)
        context_dict['category_name'] = category.name

        pages = Page.objects.filter(category=category)

        context_dict['pages'] = pages

        context_dict['category'] = category

        context_dict['slug'] = category_name_slug
    except Category.DoesNotExist:
        pass

    return render(request, 'rango/category.html', context_dict)
    #return HttpResponseRedirect(reverse('rango:category', args=context_dict))
    #^ not working

在访问localhost:8000 / rango时,收到以下错误消息:

NoReverseMatch at /rango/

Reverse for 'category' with arguments '(u'other-frameworks',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'rango/category/(?P<category_name_slug>[\\w]+)/$']

我做错了什么? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

正则表达式中与'other-frameworks'匹配的部分是[\w]+\w-不匹配,因此没有模式匹配该slug。如果您希望它们与slug匹配,请为您的模式添加-,例如[-\w]+