Thomas Michaelides
Thomas Michaelides

Reputation: 77

Django URL directing to wrong view

I am creating a Django application and have a couple URL'S

path('survey/<url_id>/<token>/', views.take_questionnaire, name='take-survey'),
path('survey/results/<url_id>/', views.view_results, name='view-results'),

I am trying to access the 'view-results' url - http://127.0.0.1:8000/survey/results/lqH16jwM19Y6LLd/ - but for some reason this is triggering the 'take-survey' url. If i change the order of the urls they seem to work, but im curious as to what is causing this.

I have never encountered this before, maybe i missed something when learning about django urls. Could someone explain why the first URL is getting triggered rather than the second?

Upvotes: 1

Views: 181

Answers (2)

Daniel Oram
Daniel Oram

Reputation: 8411

Move the view-results route above the take-survey route.

url patterns are parsed in order and take-survey is being returned because the url /survey/results/lqH16jwM19Y6LLd/ fits survey/<url_id>/<token>/ as well as the view-results pattern.

Changing the order ensures any url /survey/results/some-id/ will always go to view-results.

path('survey/results/<url_id>/', views.view_results, name='view-results'),
path('survey/<url_id>/<token>/', views.take_questionnaire, name='take-survey'),

Upvotes: 0

NKSM
NKSM

Reputation: 5854

The urls are very similar.

All two urls match strings on second and third place.

If you change view-results to:

path('survey/results/view/<url_id>/', views.view_results, name='view-results'),

It will be work.

Look also at examples from Django.

Upvotes: 2

Related Questions