【发布时间】:2020-06-26 06:44:08
【问题描述】:
无论我使用clean() 还是clean_initial_ph(),我都会收到重复的错误消息。
如果我遍历表单字段:
{% for field in form %}
{{ field|as_crispy_field }}
{% if form.errors %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif%}
{% endfor %}
或手动列出字段和错误:
...
{{ form.initial_ph|as_crispy_field }}
{{ form.initial_ph.errors }}
...
我仍然收到重复的错误消息(尽管较大的错误消息的样式不同)。
我关注了validation guidelines。例如在clean_initial_ph() 我的验证看起来像这样:
def clean_initial_ph(self):
initial_ph = self.cleaned_data['initial_ph']
if initial_ph:
if initial_ph < 0:
raise forms.ValidationError(_("PH must be above 0."), code = 'negative_intial_ph')
return initial_ph
我对@987654332@ 中的某些时间字段进行了另一个验证,它不显示重复的错误消息:
# Assuming clean_initial_ph is commented out
def clean(self):
cleaned_data = super().clean()
pump_time = cleaned_data.get("pump_time")
disposal_time = cleaned_data.get("disposal_time")
incorptime = cleaned_data.get("incorptime")
initial_ph = cleaned_data.get("initial_ph")
disposal_ph = cleaned_data.get("disposal_ph")
if pump_time and disposal_time: # DOES NOT DISPLAY DUPLICATE ERROR MESSAGES
if pump_time >= disposal_time:
self.add_error('pump_time','Pump time must be prior to disposal time.')
self.add_error('disposal_time','Disposal time must be after to pump time.')
if incorptime:
if incorptime <= disposal_time:
self.add_error('incorptime','Incorp time must be after to disposal time.')
if initial_ph: # DOES DISPLAY DUPLICATE ERROR MESSAGES
if initial_ph < 0:
self.add_error('initial_ph','PH must be above 0.')
if disposal_ph: # DOES DISPLAY DUPLICATE ERROR MESSAGES
if disposal_ph < 0:
self.add_error('disposal_ph','PH must be above 0.')
这里发生了什么?欢迎任何想法 - 谢谢!
【问题讨论】:
-
您同时使用 clean 和 clean_field_name 方法?如果您在 clean_field_name 方法中验证,则不应在 clean 中再次验证,反之亦然。实际上,在 clean 中,您应该仅在需要多个字段以确保数据完整性时才进行验证。
-
我实际上并没有同时使用它们 - 我只是尝试了两个选项调试。
标签: python django forms validation