uses uses - 18 days ago 7
Python Question

How to use underscore to separate named group in Django URL?

I am new to django field and would like to seek help from django masters.

Now my URL has two named groups (product_slug and platform_slug) separated by "/" as below:

/search/canon-eos-1d-x-mark-ii/dc-fever


Current URL Config:

url(r'^search/(?P<product_slug>[\w\-]+)$', CustomSearchView(), name='search_result_detail'),
url(r'^search/(?P<product_slug>[\w\-]+)/(?P<platform_slug>[\w\-]+)$', CustomSearchView(), name='search_result_platform'),


I would like to use underscore as separator to make the URL short and clean:

/search/canon-eos-1d-x-mark-ii_dc-fever


Seems it's not easy to use separator other than "/" to separate Named Groups.
Are there any other solutions?

Answer

It's a regular expression, you can use any characters you like. The only thing is that you need to be more restrictive in your capturing groups, since \w also matches underscores.

url(r'^search/(?P<product_slug>[0-9a-z-]+)_(?P<platform_slug>[0-9a-z-]+)$'