另一个Django形式问题-.- 所以,我有这个可以正常工作的表格,但是不会显示任何错误消息。我对定制表单还很陌生,所以我的问题是,是否需要指定其他任何内容才能显示消息? Forms.py文件
class UserLoginForm(AuthenticationForm):
error_css_class = "error"
def __init__(self,*args,**kwargs):
super(UserLoginForm, self).__init__(*args,**kwargs)
username = forms.CharField(widget=forms.TextInput(
attrs={'class': 'input','placeholder': 'Username','label':''}
))
password = forms.CharField(widget=forms.PasswordInput(
attrs={'class': 'input','placeholder': 'Password','label':''}
))
HTML文件:
{%block content%}
<form class="form" method="POST">
{% csrf_token %}
<fieldset class="form-group text-center text-uppercase">
<h1 class="sign-in__header">Sign up</h1>
{% for field in form %}
<p>
{{ field }}
{{ field.help_text }}
</p>
{% endfor %}
</fieldset>
<div class="form-group">
<button class="submit" type="submit">Sign in</button>
</div>
{% for field in form %}
<div>{{ field.errors}}</div>
{% endfor %}
</div>
</form>
</div>
{%endblock content%}
答案 0 :(得分:0)
尝试一下:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ error }} </p>
{% endfor %}
{% endfor %}
{% endif %}
答案 1 :(得分:0)
如果表单无效时您仍停留在同一视图上,则在模板中,可以通过将错误传递给视图来访问此错误。
def View(request):
form = myForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/yourview/')
return render(request, 'template.html', {'form': form})
然后在模板中
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}