Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Login and redirect to user profile page

Tags:

python

django

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 /accounts/profile/: Django - after login, redirect user to his custom page --> mysite.com/username. I would like to use dynamic url naming to achieve this solution.

For example, what if my account landing page has the following url pattern?

url(r'^account/(?P<pk>\d+)/(?P<name>\w+)/$', AccountLanding.as_view(), name="account-landing" )`.

How would I pass the args in settings.py for LOGIN_REDIRECT_URL?

like image 543
thefoxrocks Avatar asked Mar 18 '16 19:03

thefoxrocks


1 Answers

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'
like image 102
Alasdair Avatar answered Oct 14 '22 02:10

Alasdair