I have a custom login url/view/template. I use the @login_required decorator for a page (let 's call it my_page) that requires login. Attempting to access
my_site.com/my_page
correctly calls
my_site.com/login/?next=/my_page/
BUT my view is unable to parse out the value of ?next=/my_page/my and instead always redirects to my default which is /qa/ in my view:
def login_with_email(request):
error = ''
if request.method == 'POST':
if not request.POST.get('email', ''):
error = 'Please enter your email and password'
if not request.POST.get('password', ''):
error = 'Please enter your email and password'
if not error:
email = request.POST['email']
password = request.POST['password']
try:
user = User.objects.get(email=email)
user = authenticate(username=user.username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# ***
next_page = request.GET.get('next', '/qa/')
response = HttpResponseRedirect(next_page)
# ***
response.set_cookie('login_email', email, max_age=14*24*60*60)
return response
except User.DoesNotExist:
error = 'Invalid email and password combination'
Urls.py:
url(r'^login/$', views.login_with_email),
Per my comment below, I realized I had to grab the value of next from the url before my POST processing (thanks to @Anentropic for flashing on the lightbulb). So now I grab the value of next, pass it to my template where I store it in a hidden field, and finally access it when required for the redirect using request.POST.get:
Revised view:
def login_with_email(request):
error = ''
next = request.GET.get('next', '/qa/profile/private/')
if request.method == 'POST':
...
if user.is_active:
login(request, user)
next = request.POST.get('next', '/qa/profile/private/')
...
return render(request, 'qa/login_with_email.html', {'error': error, 'login_email': login_email, 'next': next,})
And in my template:
<form method="post" action="." autocomplete="on">{% csrf_token %}
<p><input type="hidden" name="next" value="{{ next }}"/></p>
...
Note: This answer was originally posted by the poser of the question. I just moved it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With