[Fixed]-URL routing in the Django framework

1👍

To get the path in the browser to change you need to use an actual http redirect, not just a fallback in Django url matching.

# my_site/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^$', include('my_app.urls')),
    url(r'^admin/', include(admin.site.urls)),
]


# my_app/urls.py

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

from . import views

urlpatterns = [
   url(r'^profile/(?P<username>[^/]+)/$', views.profile, name='profile'),
   url(r'^profile/(?P<username>[^/]+)/(.*)?', RedirectView.as_view(pattern_name='profile')),
   url(r'^profile/$', RedirectView.as_view(pattern_name='home')),
   url(r'^$', views.profile, name="home"),
]

to explain:

  • ^profile/(?P<username>[^/]+)/$ matches mysite.com/profile/my-user-name/ with no junk at the end
  • '^profile/(?P<username>[^/]+)/(.*)?' matches the case with junk at the end (after a valid username and /) …you want to require the slash before looking for junk portion otherwise if you have two users john and johnsmith you would always match johnsmith in url as the john user (treating the smith as extra junk). We then do a real http redirect to the canonical profile url
  • '^profile/$' matches just mysite.com/profile/ and does a real http redirect to home page

for more about redirecting see: https://stackoverflow.com/a/15706497/202168

also of course the docs:
https://docs.djangoproject.com/en/1.8/ref/class-based-views/base/#redirectview
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#redirect

Leave a comment