I am having troubles with the redirect to the same page user was on after logging in, no matter how hard I tried and read all the questions here. I think it is high time I showed folks out here my code so if you can point out mistake(s). Thanks.
My login url (in base.html template):
This is present on every page. Changes to logout once the user is logged in. I read that I have to pass a param for example ‘next’ like this:
<a href="/login/?next={{request.path}}">Login</a>
but,
*The {{request.path}} is always empty. *
login view:
def mylogin(request):
"""login view"""
try:
redirect_to = request.GET.get('next', '/')
except ValueError:
redirect_to = "/"
errors = ''
t = loader.get_template('login.html')
# check for POST data
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
return HttpResponseRedirect(redirect_to)
else:
c = Context({
'errors':'disabled',
})
return HttpResponse("disabled")
else:
c = Context({
'errors':'incorrect',
})
return HttpResponse(t.render(c))
else:
c = Context({
'errors':None,
})
return HttpResponse(t.render(c))
The login form, in login.html template
<form method="post" action="?next={{ redirect_to }}" >
<p><label for="username">Username</p>
<p></label><input type="text" name="username" value="" id="username" /></p>
<p><label for="password">Password</label></p>
<p><input type="password" name="password" value="" id="password" /></p>
<p><input type="submit" value="Login"></p>
</form>
You’re not passing
requestto the template context, so naturally it’s empty. The easiest way to get it in there is to use a RequestContext, which uses the built-in context processors to add variables to the context.The usual way to do this is to use
render_to_responsewith the extra parametercontext_instance=RequestContext(request). For some reason, you’re rendering all your templates the long way, so you’ll need to create that requestcontext yourself.You’ll also need to add
django.core.context_processors.requestto theCONTEXT_PROCESSORStuple ins settings.py.