Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django url config with multiple urls matching

Tags:

python

django

in one of our Django applications we have defined multiple urls for views.

The first URL matches a general feature with pk and a second match group. The second URL matches a subfeature with pk.

Between this two urls more urls are defined, so it is not easy to see them all at once. Or, for example, the subfeature would have its own url.py.

# old urls.py
url(r'^(?P<pk>\d+)/', views.b),
url(r'^subfeature/', views.a),

After some time letters are also allowed in pk, so we now have to change \d+ to [^/]+.

# new urls.py
url(r'^(?P<pk>[^/]+)/', views.b),
url(r'^subfeature/', views.a),

Now the subfeature breaks because the url is not correctly matched, 'subfeature' is matched as pk in the first url.

How to avoid breaking other urls when changing a url regex?

like image 775
tzanke Avatar asked Dec 03 '22 23:12

tzanke


1 Answers

There's no general answer to that. Any change that makes an url more generic may break other urls that follow it.

In this case, you can swap the urls so subfeature/ will match the subfeature url, and any other url will fall through and match views.b:

url(r'^subfeature/', views.a),
url(r'^(?P<pk>[^/]+)/', views.b),
like image 200
knbk Avatar answered Dec 19 '22 17:12

knbk