Django: HttpResponseRedirect doesnt pass RequestCo

2020-07-18 02:49发布

问题:

Basically, I'm trying to redirect people who aren't logged in to the login page.

What I'm currently using is:

return render_to_response('login.html', context_instance=RequestContext(request))

But that leaves the url at the homepage. I'd like to have it redirect to /accounts/login/, but when I use

return HttpResponseRedirect('/accounts/login/')

I get the error

Key 'username' not found in <QueryDict: {}>

I understand that to mean that I do need to have

context_instance=RequestContext(request))

Is there anyway to have a proper redirect, and still pass RequestContext along?

回答1:

RequestContext is only used to pass values to the template engine when a template is rendered. The destination view shouldn't depend on the RequestContext from the originating view, it should be able to generate it's own RequestContext.

There are situations however where you need to pass values between views like this. In these situations you can use querystring values to do so. For example...

def originating_view(request, *args, **kwargs):
    return HttpResponseRedirect('/accounts/login/?username=%s&next=%s' % (username, request.path)

def destination_view(request, *args, **kwargs):
    # Get the username from the querystring
    username = request.GET.get('username', None)
    next = request.GET.get('next', '/')

    if username:
        # ...

(Note that I'm assuming the reason you want to preserve the username is to have it pre-populated into the login form. If you're performing an actual login you'll want to be using POST instead so that the username and password aren't recorded in plain text in the URL).



标签: django http