[英]Django form.is_valid() always false
I'm coding a login.我正在编写登录信息。 When I programmed the form by hand I got it working.
当我手工编写表单时,我让它工作了。
The code below works:下面的代码有效:
views.py视图.py
def login_view(request):
if request.method == 'GET':
return render(request, 'app/login.htm')
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is None:
return HttpResponseRedirect(reverse('error'))
if not user.is_active:
return HttpResponseRedirect(reverse('error'))
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page.
return HttpResponseRedirect(reverse('home'))
template:模板:
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="30" /></p>
<p><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></p>
<input type="submit" value="Log in" />
<input type="hidden" name="next" value="" />
</form>
Great!伟大的! But now I want to do the same thing using Django's forms.
但是现在我想使用 Django 的表单来做同样的事情。
The code below is not working because I get is_valid() == False, always.下面的代码不起作用,因为我总是得到 is_valid() == False。
views.py:视图.py:
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
print form.is_valid(), form.errors, type(form.errors)
if form.is_valid():
## some code....
return HttpResponseRedirect(reverse('home'))
else:
return HttpResponseRedirect(reverse('error'))
else:
form = AuthenticationForm()
return render(request, 'app/login.htm', {'form':form})
template:模板:
<form action="{% url 'login' %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
There are a bunch of people on stackoverflow complaining that they get is_valid always false. stackoverflow 上有很多人抱怨他们得到 is_valid 总是错误的。 I have read all those posts, and as far as I can tell I'm not making any of those mistakes.
我已经阅读了所有这些帖子,据我所知,我没有犯任何这些错误。 I found a new mistake to make :-)
我发现了一个新的错误:-)
EDIT: I added a print in the code.编辑:我在代码中添加了一个打印。 The output when opening the login view and submitting is
打开登录视图并提交时的输出是
[27/Dec/2013 14:01:35] "GET /app/login/ HTTP/1.1" 200 910
False <class 'django.forms.util.ErrorDict'>
[27/Dec/2013 14:01:38] "POST /app/login/ HTTP/1.1" 200 910
and so is_valid() is False, but form.errors is empty.因此 is_valid() 为 False,但 form.errors 为空。
It turns out that Maxime was right after all (sorry) - you do need the data
parameter:事实证明,Maxime 毕竟是对的(抱歉)-您确实需要
data
参数:
form = AuthenticationForm(data=request.POST)
The reason for that, though, is that AuthenticationForm overwrites the signature of __init__
to expect the request as the first positional parameter.但是,这样做的原因是 AuthenticationForm 覆盖了
__init__
的签名,以将请求作为第一个位置参数。 If you explicitly supply data
as a kwarg, it will work.如果您明确提供
data
作为 kwarg,它将起作用。
(You should still leave out the else clause that redirects away on error, though: it's best practice to let the form re-render itself with errors in that case.) (不过,您仍然应该省略在错误时重定向的 else 子句:在这种情况下,最好让表单重新呈现错误。)
查看form.errors
这将帮助您找出原因。
If situation arises, that you don't have an option (I was trying to work with bootstrap modals and it was just not working), I had to do this, or else the modal would always trigger even if the form had not issues ( and the is_valid is always False by default )如果出现这种情况,您没有选择(我试图使用引导模态,但它不起作用),我必须这样做,否则即使表单没有问题,模态也会始终触发(并且 is_valid 默认情况下始终为 False )
What I needed:我需要什么:
In the modal template:在模态模板中:
{% if not brand_form.is_valid and brand_form.errors %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).on('load', (function() {
$('#brandAddModal').modal('show');
}));
</script>
{{ brand_form.non_field_errors }}
{% endif %}
In the view:在视图中:
def add_brand_form(request):
form = BrandForm()
if request.method == 'POST':
form = BrandForm(data=request.POST)
if form.is_valid():
return HttpResponseRedirect('/home')
else:
return render(request, template_name='home.html', context={'brand_form':form})
return render(request, template_name='modal_add_brand.html', context={'brand_form':form})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.