def login_view(request):
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user= form.get_user()
login(request, user)
if "next" in request.POST:
return redirect(request.POST.get('next'))
else:
print('failed to redirect after login')
return redirect('articles:list')
<form action='.' method="post">
{% csrf_token %}
{{ form }}
{% if request.GET.next %}
<input type="hidden" name="next" value="{{ request.GET.next }}">
{% endif %}
<input type="submit" value="Login">
</form>
So the issue I am having is that when I use the @login_required parameter on a specific view function in Django. Things work fine initially. The URL contains ?next=/original/url and the form is correctly able to collect the request.POST.next value of the dictionary it returns and send it back to the login function.
Then if you put the password in correctly, it redirects you back to the page you were originally trying to get to via the value of the request.POST.next value
THE ISSUE:
This only works if you get the password right on the first try.
If you enter the password incorrectly, it loses the ?next= part of the url tag and just goes to the default log in page. Thus, when you get the password right the second time, it does not redirect you back to the page you were trying to access (that was locked by a login requirement).
Does anyone know how to resolve this? Thanks.
CodePudding user response:
In this case, you have to check to see if the user is authenticated successfully, and handle if not. Try something like this:
def login_page(request):
form = LoginForm(request.POST or None)
context = {"form": form}
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_post or None
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, f'You are now logged in.')
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("/")
else:
messages.warning(request, f'Login error. The email address and/or password is incorrect.')
return render(request, "accounts/login.html", context)