Mr.Drk
Mr.Drk

Reputation: 13

Why urls order is important in django for different named urls?

I have two urls in my urls.py file

url('to_quotation/$', views.to_quotation, name='to_quotation'),
url('turn_into_quotation/$', views.turn_into_quotation, name='turn_into_quotation'),

and i have two view for them in views.py. When i make an ajax call to 'turn_into_quotation' url, 'to_quotation' view works. But if i changed my urls.py as:

url('turn_into_quotation/$', views.turn_into_quotation, name='turn_into_quotation'),
url('to_quotation/$', views.to_quotation, name='to_quotation'),

it works properly.

What is the reason for that?

Upvotes: 0

Views: 181

Answers (2)

Peterlits Zo
Peterlits Zo

Reputation: 536

@Alasdair's answer is amazing~ I'd like to attach more infomations:

Django use regex-like syntax to match it and split url's argument:

^to-quotation/<id: int>/$`

It will: 1. try to match the url, 2. try to split its argument from url, and here it split int-value to id.

So it is easy to know, in the url's settings, it is important to hold each sub-url cannot match another.

Upvotes: 0

Alasdair
Alasdair

Reputation: 308939

You are missing the ^ at the beginning of the regex. Change it to:

url(r'^to_quotation/$', views.to_quotation, name='to_quotation'),
url(r'^turn_into_quotation/$', views.turn_into_quotation, name='turn_into_quotation'),

Without the ^, to_quotation/$ matches to_quotation/ and also turn_into_quotation/. In that case, the order matters, because Django will use the first URL pattern that matches.

If you're using a recent version of Django, you could use path() instead, and avoid regex gotchas.

path('to_quotation/', views.to_quotation, name='to_quotation'),
path('turn_into_quotation/', views.turn_into_quotation, name='turn_into_quotation'),

Upvotes: 2

Related Questions