Karnivaurus
Karnivaurus

Reputation: 24111

Django: url dispatcher

I am trying to configure my Django url dispatcher. I want /results to render my results template, and /results/3 to render my user_results template, with an argument of 3, for example. If I use the following code:

url(r'^results/', views.results, name='results'),
url(r'^results/(\d+)/$', views.user_results, name='user_results')

then both /results and /results/3 just load render the results template. However, if I comment out the first line, then /results/3 renders the user_results template, as expected.

Why is /results/3 only matching the second url when the first one is omitted?

Upvotes: 2

Views: 179

Answers (1)

Justin O Barber
Justin O Barber

Reputation: 11591

/results/3 is matching your url pattern because your regular expression does not have the end-of-string $. Note the difference between the following:

>>> import re
>>> re.match(r'^results/', 'results/3')  # no end of string $
<_sre.SRE_Match object at 0x02BFD3D8>
>>> re.match(r'^results/$', 'results/3')

The easiest (and probably best) thing to do is to add an end-of-string $ to your first url pattern:

url(r'^results/$', views.results, name='results'),
url(r'^results/(\d+)/$', views.user_results, name='user_results')

Otherwise, you can reverse your url patterns. As soon as a matching url pattern is found, the dispatcher will stop searching through the url patterns and will dispatch immediately. Try this instead:

url(r'^results/(\d+)/$', views.user_results, name='user_results'),  # will dispatch here and stop searching url patterns if a digit occurs after results
url(r'^results/', views.results, name='results')

Upvotes: 3

Related Questions