django 1.10 url dispatcher not working

402 views Asked by At

I'm trying to simply give an app url an option of /headless/ to make it show a different template.

My project/urls.py has:

urlpatterns = [
    url(r'^datastore/', include('datastore.urls')),
]

My app/urls.py has:

app_name = 'datastore'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^datastore/(?P<headless>"headless"{1})/$', views.index,name='index'),
]

I'm getting a 404 error with the above.

I've also tried:

url(r'^datastore/(?P<headless>"headless"?)/$',
url(r'^datastore/(?P<headless>\w{1})/$', views.index, name='index'),
url(r'^datastore/(?P<headless>\w+)/$', views.index, name='index'),
2

There are 2 answers

1
nickie On BEST ANSWER

You have to remove the prefix /datastore/ from the app urlpattern:

app_name = 'datastore'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<headless>"headless"{1})/$', views.index,name='index'),
]

According to Django's documentation:

Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

So, the url pattern in your project's settings consumes the datastore/ prefix. You should be able to check that this is so by trying /datastore/datastore/headless/ (this should work with your current configuration).

Notice, however, that the combination of regular expression matches either /datastore/headless/ or /datastore// (the same in all your variations). This may not be what you want. Wilfried's answer (which does not address the real issue here) shows you how to better do what I think you intend to.

1
Wilfried On

It's may be your regex on your url.

If you need access to url :

  • /datastore/

  • /datastore/headless/

you can create two url, pointing to the same view.

urlpatterns = [
   url(r'^$', views.index, name='index'),
   url(r'^datastore/$', views.index, name='index'),
   url(r'^datastore/(?P<headless>(headless))/$', views.index, name='index'),
]

If you want, it's not necessary to use a parameter. If you have only headless like possibility.

urlpatterns = [
   url(r'^$', views.index, name='index'),
   url(r'^datastore/$', views.index, name='index'),
   url(r'^datastore/headless/$', views.index, name='index'),
]