Django - Login and redirect to user profile page

前端 未结 1 1643
说谎
说谎 2020-11-30 12:23

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 s

1条回答
  •  鱼传尺愫
    2020-11-30 12:25

    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'
    

    0 讨论(0)
提交回复
热议问题