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.
the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here.
Now, start the server and enter localhost:8000/hello to the browser. This URL will be mapped into the list of URLs and then call the corresponding function from the views file. In this example, hello will be mapped and call hello function from the views file. It is called URL mapping.
You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.
That is, url--> view name . But sometimes, like when redirecting, you need to go in the reverse direction and give Django the name of a view, and Django generates the appropriate url. In other words, view name --> url . That is, reverse() (it's the reverse of the url function).
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
For Django 1.4, you can could use reverse_lazy
LOGIN_URL = reverse_lazy('login')
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/'
In django development version reverse_lazy() becomes an option: https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With