I face a problem and I can't find a solution.
I'm trying to redirect to the previous page after login. Somehow the ?next=request.path returns none when trying to request.POST.get() after submission.
This is my Html code that directs the user to the login page, taking the request.path as "next page after login" value.
{% if user.is_authenticated %}
<button class="btn" data-toggle="modal" data-target="#inquiryModal">
<a class="btn btn-primary border rounded-0"
role="button" href="#">Make an Inquiry</a>
</button>
{% else %}
<a class="btn btn-primary border rounded-0" role="button"
href="{% url 'login' %}?next={{ request.path|urlencode }}"
>Make An Inquiry</a>
{% endif %}
This is the login page html code.
<div class="login-clean" style="background-color: #fff;">
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<!--- ALERTS -->
{% include 'partials/_alerts.html' %}
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="Email"></div>
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">Log In</button>
</div>
</form>
</div>
Views.py file
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
valuenext = request.POST.get('next')
print(valuenext)
user = auth.authenticate(username=email, password=password)
# if user is found and not from listing page login and redirect to dashboard
if user is not None and valuenext == "":
auth.login(request, user)
messages.success(request, 'You are now succesfully logged in')
return redirect('dash_inquiries')
# if user is found and from specific listing page login and redirect to the listing
elif user is not None and valuenext != "":
auth.login(request, user)
print("success")
messages.success(request, 'You are now logged in')
return redirect(valuenext)
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
What am I doing wrong here? The next value is passed in the url when directing to the login page, but I don't seem to correctly get() the next value in my backend as it keeps returning None.
Thanks in advance.
Okay, so I didn't make sure I passed the next value into the login form, therefore the solution was to add a hidden input to get the next value in the request:
<input type="hidden" name="next" value="{{ request.GET.next }}" />