提交表单时,我对登录页面的重定向无法正常工作。
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)
我希望它重定向到同一页面并打印输出,使我知道身份验证有效。但这是实际发生的情况。
Page not found(404)
Request Method: GET
Request URL:http://127.0.0.1:8000/login/POST?username=stone&password=pass
关于发生了什么的任何想法吗?
答案 0 :(得分:3)
您还没有显示模板,但是看起来您的action="POST"
标签中包含method="POST"
而不是form
。
答案 1 :(得分:0)
请确保您的template.html如下所示:
<form method="post">
{% csrf_token %}
{{ form }}
</form>
答案 2 :(得分:0)
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,
})