43

A few of the options in the django settings file are urls, for example LOGIN_URL and LOGIN_REDIRECT_URL. Is it possible to avoid hardcoding these urls, and instead use reverse url mapping? At the moment this is really the only place where I find myself writing the same urls in multiple places.

TM.
  • 108,298
  • 33
  • 122
  • 127

2 Answers2

60

Django 1.5 and later

As of Django 1.5, LOGIN_URL and LOGIN_REDIRECT_URL accept named URL patterns. That means you don't need to hardcode any urls in your settings.

LOGIN_URL = 'login'  # name of url pattern

For Django 1.5 - 1.9, you can also use the view function name, but this is not recommended because it is deprecated in Django 1.8 and won't work in Django 1.10+.

LOGIN_URL = 'django.contrib.auth.views.login' # path to view function

Django 1.4

For Django 1.4, you can could use reverse_lazy

LOGIN_URL = reverse_lazy('login')

Django 1.3 and earlier

This is the original answer, which worked before reverse_lazy was added to Django

In urls.py, import settings:

from django.conf import settings

Then add the url pattern

urlpatterns=('',
    ...
    url('^%s$' %settings.LOGIN_URL[1:], 'django.contrib.auth.views.login', 
        name="login")
    ...
)

Note that you need to slice LOGIN_URL to remove the leading forward slash.

In the shell:

>>>from django.core.urlresolvers import reverse
>>>reverse('login')
'/accounts/login/'
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • 1
    Ah, good solution, I didn't consider going from settings -> urls, only the other way around. +1 – TM. Oct 05 '09 at 12:12
  • And can you avoid hard-coding the django root, so that /accounts/login resolves to /root/accounts/login if your django app is deployed on example.com/root rather than example.com/ ? – gozzilli Nov 06 '13 at 06:23
  • @gozzilli - since Django 1.4, I would use `reverse_lazy` instead of importing `settings.LOGIN_URL` into the urls. I've updated the answer. – Alasdair Nov 06 '13 at 08:04
  • For me with Django 2.1 the LOGIN_URL_REDIRECT with name of url pattern ist not working. It gives me a 404 error and {'path':'name_of_url'}. Has there something changed? In the documentation I can't finde anything. – Tobit Mar 21 '19 at 10:52
  • @tobit please asks new question, you haven’t provided enough information to show what the problem is. There shouldn’t be any changes in Django 2.1 that effect this. – Alasdair Mar 21 '19 at 13:33
14

In django development version reverse_lazy() becomes an option: https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy

linqu
  • 11,320
  • 8
  • 55
  • 67
Bas Koopmans
  • 341
  • 4
  • 14