Currently I use these patterns to log in and out
urlpatterns += patterns("",
(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
(r'^logout/$', 'django.contrib.auth.views.logout', {'template_name': 'logout.html'})
)
Inspite of having LOGIN_REDIRECT_URL = '/profile/' in my settings.py, Django does not send me to /profile/ if I want to access /login/ when I'm already logged in...
Can I somehow redirect in the URL patterns of the auth system? I'm reluctant to write a custom view for that.
Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .
auth. views. login redirects you to accounts/profile/ right after you log in.
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. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.
redirect() Returns an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: A model: the model's get_absolute_url() function will be called.
I ended up writing a decorator for such task.
Please take note that I've made it quick & dirty.
from django.conf import settings
from django.shortcuts import redirect
def redirect_if_logged(f=None, redirect_to_url=None):
u"""
Decorator for views that checks that the user is already logged in, redirecting
to certain URL if so.
"""
def _decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
redirect_url = redirect_to_url
if redirect_to_url is None:
# URL has 'next' param?
redirect_url_1 = request.GET.get('next')
# If not, redirect to referer
redirect_url_2 = request.META.get('HTTP_REFERER')
# If none, redirect to default redirect URL
redirect_url_3 = settings.LOGIN_REDIRECT_URL
redirect_url = redirect_url_1 or redirect_url_2 or redirect_url_3
return redirect(redirect_url, *args, **kwargs)
else:
return view_func(request, *args, **kwargs)
return _wrapped_view
if f is None:
return _decorator
else:
return _decorator(f)
On your projects urls.py
file (url_patterns
list), add redirect_authenticated_user=True
as a parameter in login path like this:
path('admin/', admin.site.urls),
path('login/', auth_views.LoginView.as_view(
template_name='blog_app/login.html',
redirect_authenticated_user=True
), name='login'),
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