Title: Multiple argument URLs in Django
Tags: python;django
Question: 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&gt;[0-9]{4})/(?P<month&gt;[0-9]{2})/$', views.month_archive),
Which I did, as:
url(u'^(?P<Name&gt;.*)/(?P<ThreadName&gt;.*)/$', 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.


Here is another answer: You need to make the capturing part non-greedy. Replace:
url(u'^(?P<Name&gt;.*)/(?P<ThreadName&gt;.*)/$', views.thread, name = "thread"),
url(u'^(?P<Name&gt;.*?)/(?P<ThreadName&gt;.*?)/$', 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&gt;\w+)/(?P<ThreadName&gt;\w+)/$', views.thread, name = "thread"),

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:01/27/16', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<python><django>', 'Title': 'Multiple argument URLs in Django', 'ViewCount': 40, 'id': 35028561, 'user_AboutMe': "<p>A newbie programmer who's decent with C++ and trying to learn Haskell. I used this as a reference before eventually signing up.</p>\n", 'user_AccountId': 1756202.0, 'user_DisplayName': 'Sam Shippey', 'user_Reputation': 23.0, 'user_Views': 6.0, 'user_id': 3163486.0}}