Skip to content Skip to sidebar Skip to footer

Django - Login And Redirect To User Profile Page

I am trying to redirect a user who just logged in to his/her's respective account page. This question has been asked a few times, but most of them are old and use static urls like

Solution 1:

It isn't possible to use dynamic arguments (e.g. the primary key of the logged in user) in the LOGIN_REDIRECT_URL in your settings.py.

In Django 1.11+, you can subclass LoginView, and override get_success_url so that it dynamically redirects.

from django.contrib.auth.views import LoginView

class MyLoginView():

    def get_success_url(self):
        url = self.get_redirect_url()
        return url or reverse('account_landing', kwargs={'pk': self.request.user.pk, 'name': self.request.user.username})

Note the url = self.get_redirect_url() line is required to handle redirects back to the previous page using the querystring, e.g. ?next=/foo/bar

Then use your custom login view in your URL config.

url(r'^login/$', MyLoginView.as_view(), name='login'),

For earlier versions of Django, it isn't possible to customise the function-based login view in the same way.

One work around is to create a view that redirects to your landing page:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def account_redirect(request):
    return redirect('account-landing', pk=request.user.pk, name=request.user.username)

Create a url pattern for this view:

urlpatterns = [
    url(r'^account/$', account_redirect, name='account-redirect'),
]

Then use that view as LOGIN_REDIRECT_URL:

LOGIN_REDIRECT_URL = 'account-redirect'

Solution 2:

On Django 4.x there is a new attribute called next_page and you can use it as:

from django.contrib.auth.views import LoginView
from django.urls import reverse_lazy

class MyLoginView():
...
next_page = reverse_lazy('profile', kwargs={'id': pk},
                            name='username'))
...

Post a Comment for "Django - Login And Redirect To User Profile Page"