Answers:
如果在表单无效时渲染同一视图,则可以在模板中使用来访问表单错误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(request, 'my_template.html', {'form': form})
UNIQUE constraint failed:
例外吗?
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>
messages.error(request, "Error")
?
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})
更新: 添加了关于表单集错误的更详细的描述。
Form.errors组合了所有field和non_field_errors。因此,您可以将html简化为:
模板
{% 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 %}
form_tags.py
from django import template
register = template.Library()
def get_label(a_dict, key):
return getattr(a_dict.get(key), 'label', 'No label')
register.filter("get_label", get_label)
一个警告:与表单相比,Formset.errors不包含non_field_errors。
您可以简单地这样做,因为在初始化表单时,表单中还包含表单数据和无效数据:
def some_func(request):
form = MyForm(request.POST)
if form.is_valid():
//other stuff
return render(request,template_name,{'form':form})
如果除模板外,if会引发模板中的错误,但表单数据仍将保持为:
您可以仅放置一个标志变量,在这种情况下为is_successed。
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 %}