Reputation: 1
My redirect for my login page is not working correctly when I submit a form.
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form': form,
}
print(request.user.is_authenticated)
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:
print(request.user.is_authenticated)
login(request, user)
# Redirect to a success page.
return redirect("login")
else:
# Return an 'invalid login' error message.
print("Error")
return render(request, "content/login.html", context)
I am expecting it to redirect to same page and print an output that lets me know the authentication worked. But this is what actually happens..
Page not found(404)
Request Method: GET
Request URL:http://127.0.0.1:8000/login/POST?username=stone&password=pass
Any idea as to what is going on?
Upvotes: 0
Views: 44
Reputation: 333
def login_user(request):
if request.user.is_authenticated():
return redirect(reverse('homepage'))
form = LoginForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
if user is not None:
login(request, user)
return redirect(reverse('homepage'))
else:
error_message = "* Password you entered is incorrect."
return render(request, "account/login.html",{
"form": form,
"error_message": error_message,
})
else:
return render(request, "account/login.html", {
"form": form,
})
Upvotes: 0
Reputation: 326
Be sure, that your template.html looks like this:
<form method="post">
{% csrf_token %}
{{ form }}
</form>
Upvotes: 0
Reputation: 308779
You haven't shown your template, but it looks like you have action="POST"
instead of method="POST"
in your form
tag.
Upvotes: 3