tags:

views:

178

answers:

1

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?

+3  A: 

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).

T. Stone
Thanks for the reply. I realized that my problem was rather stupid and had nothing to do with what I posted above.Turns out I forgot to pass a context_instance in my login view...However, your comment actually helped me elsewhere, so thanks a ton!
Dane Larsen