Ivan Ivanov
Ivan Ivanov

Reputation: 2052

Django urls with the same name but different regexps

I have these types of urls:

/city/  
/city/category/  
/city/category/subcategory/ 

All of the urls are handling by one view. Is there a way to use the same name for these urls to subsequently use tags like these:

{% url 'city_index' city.slug %},
{% url 'city_index' city.slug category.slug %},
{% url 'city_index' city.slug category.slug subcategory.slug %}

I tried this:

url(r'^(?P<city_slug>[\w\-]+)/$',
    'real_city_index',
    name='city_index'
),
url(r'^(?P<city_slug>[\w\-]+)/(?P<category_slug>[\w\-]*)/{0,1}$',
    'real_city_index',
    name='city_index'
),

But in that case the second url reverse returns url without trailing slash.

If you do not write /{0,1}, urls like /city/category won't work, that is worse than reversing without slash.

Upvotes: 1

Views: 3660

Answers (2)

jro
jro

Reputation: 9474

Django has named URL patterns for this. The problem with your code is that you use city_index for all of the url's name properties. Change these to name='city_index', name='city_category' and name='city_subcategory' and all should be well. The view name (real_city_index) can be the same for all url patterns.

Upvotes: 3

markijbema
markijbema

Reputation: 4055

Is there a good reason not to call them 'city_index', 'city_index_with_category' and 'city_index_with_sub_category'?

Upvotes: 5

Related Questions