我是Django表单,它可以检查表单是否有效:
if form.is_valid():
return HttpResponseRedirect('/thanks/')
但如果它无效,我会错过怎么办?如何返回带有错误消息的表单?我没有在任何例子中看到“其他”。
答案 0 :(得分:187)
如果您在表单无效时呈现相同的视图,那么在模板中您可以access the form errors using form.errors
。
{% 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 %}
一个例子:
def myView(request):
form = myForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
return HttpResponseRedirect('/thanks/')
return render_to_response('my_template.html', {'form': form})
答案 1 :(得分:9)
<强> views.py 强>
from django.contrib import messages
def view_name(request):
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks'/)
else:
messages.error(request, "Error")
return render(request, 'page.html', {'form':form_class()})
如果你想要显示除了无效之外的表格的错误,只需将{{form.as_p}}放入我在下面所做的内容
<强> page.html中强>
<html>
<head>
<script>
{% if messages %}
{% for message in messages %}
alert(message);
{% endfor %}
{% endif %}
</script>
</head>
<body>
{{form.as_p}}
</body>
</html>
答案 2 :(得分:4)
更新: 添加了对表单集错误的更详细描述。
Form.errors组合了所有field和non_field_errors。因此,您可以将html简化为:
模板
if (vec.size() > 2) result.emplace_back(vec[2]);
if (vec.size() > 3) result.emplace_back(vec[3]);
form_tags.py
{% load form_tags %}
{% if form.errors %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% for key, value in form.errors.items %}
<span class="fieldWrapper">
{{ key }}:{{ value }}
</span>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
If you want to generalise it you can create a list_errors.html which you include in every form template. It handles form and formset errors:
{% if form.errors %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% for key, value in form.errors.items %}
<span class="fieldWrapper">
{{ key }}:{{ value }}
</span>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% elif formset.total_error_count %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% if formset.non_form_errors %}
{{ formset.non_form_errors }}
{% endif %}
{% for form in formset.forms %}
{% if form.errors %}
Form number {{ forloop.counter }}:
<ul class="errorlist">
{% for key, error in form.errors.items %}
<li>{{form.fields|get_label:key}}
<ul class="errorlist">
<li>{{error}}</li>
</ul>
</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
一个警告:与Formset相比,错误不包括non_field_errors。
答案 3 :(得分:3)
def some_view(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks'/)
else:
form = SomeForm()
return render(request, 'some_form.html', {'form': form})
答案 4 :(得分:3)
This answer 是正确的,但有一个问题:未定义字段。 如果您有多个字段,您将无法识别哪个字段有错误。
通过此更改,您可以显示字段名称:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ field.label }}</strong><span>{{ 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 %}
答案 5 :(得分:1)
@AamirAdnan的答案缺少field.label
;另一种显示错误的方式是几行。
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
答案 6 :(得分:0)
只需执行以下操作即可,因为初始化表单时,其中还包含表单数据和无效数据:
def some_func(request):
form = MyForm(request.POST)
if form.is_valid():
//other stuff
return render(request,template_name,{'form':form})
if会在模板中引发错误(如果有的话),但表单数据仍将保持为:
答案 7 :(得分:-1)
您可以简单地放置一个标志变量,在这种情况下,已成功。
def preorder_view(request, pk, template_name='preorders/preorder_form.html'):
is_successed=0
formset = PreorderHasProductsForm(request.POST)
client= get_object_or_404(Client, pk=pk)
if request.method=='POST':
#populate the form with data from the request
# formset = PreorderHasProductsForm(request.POST)
if formset.is_valid():
is_successed=1
preorder_date=formset.cleaned_data['preorder_date']
product=formset.cleaned_data['preorder_has_products']
return render(request, template_name, {'preorder_date':preorder_date,'product':product,'is_successed':is_successed,'formset':formset})
return render(request, template_name, {'object':client,'formset':formset})
然后在模板中,您只需将代码放在下面
{%if is_successed == 1 %}
<h1>{{preorder_date}}</h1>
<h2> {{product}}</h2>
{%endif %}