Django picks up wrong urs in application urs.py

17 views
Skip to first unread message

Tsuyoshi Takahashi

unread,
Dec 18, 2017, 10:19:47 PM12/18/17
to Django users
when application urs.py decribed as below
urlpatterns = [
url('card', views.card),
url('welcome', views.welcome),
url('cards', views.cards),
]

Django picks up "url('card', views.card)" when I enter "http://localhost:8000/firstApp/cards/" and
"http://localhost:8000/firstApp/card/".

But when I changed application urs.py as below
urlpatterns = [
url('cards', views.card),
url('welcome', views.welcome),
url('card', views.cards),
]
Django picks up "url('cards', views.card)" when I enter "http://localhost:8000/firstApp/cards/" and
Django picks up "url('card', views.card)" when I enter "http://localhost:8000/firstApp/card/". This
action is what Iexpected.

Is this a specification of Django or bug?

Lachlan Musicman

unread,
Dec 18, 2017, 10:58:56 PM12/18/17
to django...@googlegroups.com
Did you restart the webserver?

cheers
L.

James Schneider

unread,
Dec 19, 2017, 12:17:11 AM12/19/17
to django...@googlegroups.com


On Dec 18, 2017 7:19 PM, "Tsuyoshi Takahashi" <go.tak...@gmail.com> wrote:
when application urs.py decribed as below
urlpatterns = [
url('card', views.card),
url('welcome', views.welcome),
url('cards', views.cards),
]

Django picks up "url('card', views.card)" when I enter "http://localhost:8000/firstApp/cards/" and
"http://localhost:8000/firstApp/card/".

To me, this is expected and correct behavior. 

Django will take the first match, not necessarily the best match. The word 'card' is contained in both 'card' and 'cards', and I believe Django uses re.match() or a similarly behaving regex parser. Since your 'card' URL is defined first, it matches. As you've shown, changing the order produces the desired result.

The real fix is to properly terminate your URL regular expressions to match as you desire so that the order doesn't matter. Try defining your URL's like this:

urlpatterns = [
url(r'card/$', views.card),
url(r'welcome/$', views.welcome),
url(r'cards/$', views.cards),
]

The extra /$ at the end indicates that the URL will end with a /. That should be enough to differentiate the requests.

See the URL dispatcher documentation: 


If you aren't familiar with regular expressions, also see the Python re module documentation:


-James
Reply all
Reply to author
Forward
0 new messages