Django after @login_required redirect to next

后端 未结 4 1176
耶瑟儿~
耶瑟儿~ 2020-12-25 08:46

I feel like this is an easy question and I\'m just missing 1 small step.

I want to do any number of the following (as the term in the next parameter):



        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-25 08:52

    The query string is implicitly passed to any view, without you having to write any special code.

    All you have to do is make sure that the next key is passed from the actual login form (in your case, this is the form that is rendered in /accounts/login/), to the /accounts/auth view.

    To do that, you need to make sure you have the request template context processor (django.core.context_processors.request) enabled in your settings. To do this, first you need to import the default value for TEMPLATE_CONTEXT_PROCESSORS, then add the request processor to it in your settings.py, like this:

    from django.conf import global_settings
    
    TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
        "django.core.context_processors.request",
    ) 
    

    Then in the form:

    {% csrf_token %} {{ login_form }}

    Now, in your /accounts/auth view:

    def foo(request):
        if request.method == 'POST':
            # .. authenticate your user
    
    
            # redirect to the value of next if it is entered, otherwise
            # to /accounts/profile/
            return redirect(request.POST.get('next','/accounts/profile/'))
    

提交回复
热议问题