Django: no reverse url match with multiple paramet

2019-07-22 14:56发布

问题:

My URLs need to capture the following:

domain/forum-name/
domain/forum-name/topic-name

I have the following URL definitions:

url(r'^$', views.index_forums, name='index_forums'),
url(r'^(?P<forum_name>[-\w]+)/(?P<topic_name>[-\w]+)/$', views.show_topic, name='show_topic'),
url(r'^(?P<forum_name>[-\w]+)/$', views.index_topics, name='index_topics'),

When I hit a URL like domain/name-of-forum, I generate URLs in the HTML like so:

{% url 'board:show_topic' forum_name|lower topic.title|lower %}

This gives me a "Reverse...not found" error, and I cannot figure out why. Am I using "url" incorrectly? Is there a problem with my regular expression? Thanks!

Edit: adding full error and template:

NoReverseMatch at /random/
Reverse for 'show_topic' with arguments '(u'random', u'funny youtube videos')' and keyword    arguments '{}' not found.
Request Method: GET
Request URL:    http://localhost:8000/random/
Django Version: 1.5c2
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'show_topic' with arguments '(u'random', u'funny youtube videos')' and keyword arguments '{}' not found.
Exception Location: /Users/travis/code/penv/lib/python2.7/site- packages/django/template/defaulttags.py in render, line 424
Python Executable:  /Users/travis/code/penv/bin/python
Python Version: 2.7.2

Reverse for 'show_topic' with arguments '(u'random', u'funny youtube videos')' and keyword arguments '{}' not found.
1   {% extends "board/base.html" %}
2   
3   {% block content %}
4   {% if topic_list %}
5   <ul>
6   {% for topic in topic_list %}
7       <li><a href="{% url 'board:show_topic' forum_name|lower topic.title|lower %}">{{topic.title}}</a></li>
8   {% endfor %}
9   </ul>
10  {% else %}
11  <p>No topics! <a href="/topic/new/">Make a new one</a>.</p>
12  {% endif %}
13  {% endblock %}

回答1:

Try:

{% url 'show_topic' forum_name|lower topic_name|lower %}

Edit:

Your url regex doesn't accept spaces:

Try:

url(r'^(?P<forum_name>[-\w]+)/(?P<topic_name>[-\w\ ]+)/$', views.show_topic, name='show_topic'),