Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect if already logged in through Django urls?

Tags:

django

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.

like image 758
Jurudocs Avatar asked Sep 01 '13 12:09

Jurudocs


People also ask

How do I redirect one page to another in Django?

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

Which of the following will redirect a user to profile mine after successful login?

auth. views. login redirects you to accounts/profile/ right after you log in.

What is reverse redirect in Django?

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.

Which Django function returns an HttpResponseRedirect to the appropriate URL for the arguments passed?

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.


2 Answers

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)
like image 72
ssebastianj Avatar answered Oct 06 '22 00:10

ssebastianj


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'),
like image 35
Aven Desta Avatar answered Oct 06 '22 01:10

Aven Desta