Home » Django » django urls without a trailing slash do not redirect

django urls without a trailing slash do not redirect

Posted by: admin November 30, 2017 Leave a comment


I’ve got two applications located on two separate computers. On computer A, in the urls.py file I have a line like the following:

(r'^cast/$', 'mySite.simulate.views.cast')

And that url will work for both mySite.com/cast/ and mySite.com/cast. But on computer B I have a similar url written out like:

(r'^login/$', 'mySite.myUser.views.login')

For some reason on computer B the url mySite.com/login/ will work but mySite.com/login will hang and won’t direct back to mySite.com/login/ like it will on computer A. Is there something I missed? Both url.py files look identical to me.


check your APPEND_SLASH setting in the settings.py file

more info in the django docs


Or you can write your urls like this:

(r'^login/?$', 'mySite.myUser.views.login')

The question sign after the trailing slash makes it optional in regexp. Use it if for some reasons you don’t want to use APPEND_SLASH setting.


This improves on @Michael Gendin’s answer. His answer serves the identical page with two separate URLs. It would be better to have login automatically redirect to login/, and then serve the latter as the main page:

from django.conf.urls import patterns
from django.views.generic import RedirectView

urlpatterns = patterns('',
    # Redirect login to login/
    (r'^login$', RedirectView.as_view(url = '/login/')),
    # Handle the page with the slash.
    (r'^login/', "views.my_handler"),


I’ve had the same problem too. My solution was put an (|/) before the end line of my regular expression.

url(r'^artists/(?P[\d]+)(|/)$', ArtistDetailView.as_view()),


I’ve had the same problem. In my case it was a stale leftover from some old version in urls.py, from before staticfiles:

url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'),
    kwargs={'document_root': settings.MEDIA_ROOT}),

MEDIA_URL was empty, so this pattern matched everything.