TheEarlyMan
TheEarlyMan

Reputation: 402

Django URL weird behaviour

I've been trying to code a simple app, and came across this weird issue. Look below, my urls.py, first:

This is my urls.py file:

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^(?P<label_slug>[\w-]+)/$', views.tasks, name='tasks'),
url(r'^add-label/$', views.add_label, name='add_label'), # this URL is acting funny
url(r'(?P<label_slug>[\w\-]+)/add_task/$', views.add_task, name='add_task'),
]

so whenever I access my third url (/add) it is going to a 404 error page, but when I add something like label/add, it seems to work. Can someone tell me how to fix this thing?

This is what the 404 error page says:

Page not found (404)
Request Method:     GET
Request URL:    http://localhost:8000/tasks/add/
Raised by:  tasks.views.tasks

No TaskLabel matches the given query.

Upvotes: 0

Views: 107

Answers (1)

bakkal
bakkal

Reputation: 55448

Your URL '^(?P<label_slug>[\w-]+)/$' is swallowing the /add-label thinking it's the slug of a task and calls the view tasks.views.tasks

List URL regex in their ascending order of genericity

As a good practice you should always put the more generic regex URLs at the bottom, since the URLs are evaluated in that order

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^add-label/$', views.add_label, name='add_label'),
    url(r'^(?P<label_slug>[\w-]+)/$', views.tasks, name='tasks'),
    url(r'(?P<label_slug>[\w\-]+)/add_task/$', views.add_task, name='add_task'),
]

Upvotes: 2

Related Questions