Redirect to Next after login in Django

前端 未结 5 3095
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-09 08:09

When a user accesses a url which requires login. The view decorator redirects to the login page. after the user enters his username and password how can I redirect the user to t

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-09 08:50

    Passing next to the login form and then the form passing that value on to view in a hidden input can be a bit convoluted.

    As an alternative, it's possible to use django.core.cache here.

    This way there is no need to pass anything extra to the form or to give the form an extra input field.

    def login_view(request):
        if request.method == 'GET':
            cache.set('next', request.GET.get('next', None))
    
        if request.method == 'POST':
            # do your checks here
    
            login(request, user)
    
            next_url = cache.get('next')
            if next_url:
                cache.delete('next')
                return HttpResponseRedirect(next_url)
    
        return render(request, 'account/login.html')
    

提交回复
热议问题