我正在尝试为我的网站创建一个登录表单但是当我在views.py中使用cleaning_data时,我得不到正确的数据。
这是我的代码:
views.py
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form': form
}
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_form.get("username")
password = form.cleaned_form.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect("/")
else:
print("Error")
return render(request, "auth/login.html", context)
的 forms.py
class LoginForm(forms.Form):
username = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control",
"placeholder": "Username"
}
)
)
password = forms.CharField(
widget=forms.PasswordInput(
attrs={
"class": "form-control",
"placeholder": "Password"
}
)
)
的的login.html
<form action="POST">{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
这是我填写用户名和密码字段并点击提交时得到的内容。 print(form.cleaned_data)
显示我想要使用的网址字段中有数据,但我无法访问它们。
答案 0 :(得分:6)
您的观点完全错误,请使用此
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form': form
}
if request.method == 'POST':
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect("/")
else:
print("Error")
else:
print('form not valid')
return render(request, "auth/login.html", context)
和html到
<form method="post" action="">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>
答案 1 :(得分:4)
HTML中存在错误 - 您应该使用method="post"
代替action
。现在,您正在/login/POST
发送GET,输入为查询参数,而不是/login
处的POST。这在您附上的屏幕截图中很明显。
有效表格应如下所示:
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-default">Submit</button>
</form>