Sam Shippey
Sam Shippey

Reputation: 23

Multiple argument URLs in Django

Trying to create a simple forum. How would I create a hierarchical set of named URLs in Django 1.9? The docs say to do it like this:

url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),

Which I did, as:

url(u'^(?P<Name>.*)/(?P<ThreadName>.*)/$', views.thread, name = "thread"),

and in views.py:

def thread(request, Name, ThreadName):
board = get_object_or_404(Board, Title = Name)
thread = get_object_or_404(Thread, Title = ThreadName)
context = { "board": board,
            "thread": thread,
            }
return render(request, "post/board.html", context)

but I get an error saying that "No Board matches the given query.", even though the board exists and I can get to it at site/Name, it only fails at site/Name/ThreadName.

Upvotes: 1

Views: 42

Answers (1)

alecxe
alecxe

Reputation: 473863

You need to make the capturing part non-greedy. Replace:

url(u'^(?P<Name>.*)/(?P<ThreadName>.*)/$', views.thread, name = "thread"),

with:

url(u'^(?P<Name>.*?)/(?P<ThreadName>.*?)/$', views.thread, name = "thread"),

Note the ? characters - they make all the difference.


Or, depending on what are the valid characters for the name and thread name, you can look for one or more alhanumeric (\w+) instead of any character:

url(r'^(?P<Name>\w+)/(?P<ThreadName>\w+)/$', views.thread, name = "thread"),

Upvotes: 3

Related Questions