验证错误没有显示
所以我坚持为什么验证错误没有显示这种特殊的形式。他们在我的所有其他表格上显示得很好,但不是这个。验证错误没有显示
我可以凭经验在工作中看到验证,因为当office_street_address
为零时,窗体不会保存。但form.non_field_error
似乎没有任何错误。
形式
class PremiumAgentForm(forms.ModelForm): class Meta:
model = Agent
exclude = ['field1', 'field2', ...]
def __init__(self, *args, **kwargs):
super(PremiumAgentForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
def clean(self):
cd = super(PremiumAgentForm, self).clean()
a = cd.get('office_street_address')
if a == None:
raise forms.ValidationError("Error")
return cd
HTML
<form class="row justify-content-center" enctype="multipart/form-data" method="post"> {% csrf_token %}
{% for error in form.non_field_errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{% if form.non_field_errors %}
<p style="color: red">there are errors</p>
{% else %}
<p>no errors</p> # This is always displayed.
{% endif %}
<div class="col-sm-4">
{% for field in form %}
<div class="form-group pb-3">
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text|safe }}</small>
{% endif %}
</div>
{% endfor %}
<button class="button2"><span>Submit</span></button>
</div>
</form>
views.py
def edit_profile(request): if request.method == 'POST':
form = PremiumAgentForm(request.POST, request.FILES, instance=agent)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.META['HTTP_REFERER'])
else:
agent = get_object_or_404(Agent, pk=request.user.agent.pk)
form = PremiumAgentForm(instance=agent)
return render(request, 'edit_profile.html', {'form': form})
回答:
对于您的情况,您保留表单,如果它是有效的,之后您做了重定向,即使表单无效。这应该有所帮助:
if not form.is_valid(): return render(request, 'edit_profile.html', {'form': form})
form.save()
以上是 验证错误没有显示 的全部内容, 来源链接: utcz.com/qa/258443.html