Django - use reverse url mapping in settings

后端 未结 2 968
天涯浪人
天涯浪人 2021-01-31 02:25

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 url

2条回答
  •  醉话见心
    2021-01-31 03:07

    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/'
    

提交回复
热议问题