[Fixed]-Redirect if already logged in through Django urls?

26👍

I use something like this in my urls.py:

from django.contrib.auth.views import login
from django.contrib.auth.decorators import user_passes_test


login_forbidden =  user_passes_test(lambda u: u.is_anonymous(), '/')

urlpatterns = patterns('',
    url(r'^accounts/login/$', login_forbidden(login), name="login"),

4👍

How about riding the Django login view?

Then add this little piece of code in that view:

if request.user.is_authenticated():
      # Redirect to profile

If you want to do something else in template itself for the register user:

{% if user.is_authenticated %}

3👍

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)

1👍

Looking at the source code on Github, the default login view provided by django.contrib.auth will only use LOGIN_REDIRECT_URL if the login form is submitted via a POST request, and it has no next parameter. (The docs mention this too).

The login view doesn’t actually do any checking of whether you’re authenticated already or not – so an already-authenticated user hitting the page with a standard GET request will see the login form again – just the same as an unauthenticated user.

If you want different behaviour, I’d recommend writing your own login view.

👤Ben

1👍

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'),

0👍

You could use this decorator

def login_excluded(redirect_to):
    """ This decorator kicks authenticated users out of a view """
    def _method_wrapper(view_method):
        def _arguments_wrapper(self, request, *args, **kwargs):
            if self.request.user.is_authenticated:
                return redirect(redirect_to)
            return view_method(request, *args, **kwargs)
        return _arguments_wrapper
    return _method_wrapper

Leave a comment