Django的。在自定义clean()方法中为Form.errors添加一个字段 [英] django. adding a field to Form.errors in a custom clean() method
本文介绍了Django的。在自定义clean()方法中为Form.errors添加一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个事件模型,我想在自定义的 def clean(self):
方法中放置以下验证规则:
I have an Event model that I'd like to place the following validation rule on, in a custom def clean(self):
method on the Model:
def clean(self):
from django.core.exceptions import ValidationError
if self.end_date is not None and self.start_date is not None:
if self.end_date < self.start_date:
raise ValidationError('Event end date should not occur before start date.')
哪个工作正常,除了我想在管理界面中突出显示 self.end_date
字段,通过某种方式将其提名为具有错误的字段。否则我只收到更改表单顶部出现的错误消息。
Which works fine, except that I'd like to highlight the self.end_date
field in the admin UI, by somehow nominating it as the field that has errors. Otherwise I only get the error message that occurs at the top of the change form.
推荐答案
docs
说明如何执行此操作。
The docs
explain how to do this at the bottom.
提供的示例: strong>
provided example:
class ContactForm(forms.Form):
# Everything as before.
...
def clean(self):
cleaned_data = self.cleaned_data
cc_myself = cleaned_data.get("cc_myself")
subject = cleaned_data.get("subject")
if cc_myself and subject and "help" not in subject:
# We know these are not in self._errors now (see discussion
# below).
msg = u"Must put 'help' in subject when cc'ing yourself."
self._errors["cc_myself"] = self.error_class([msg])
self._errors["subject"] = self.error_class([msg])
# These fields are no longer valid. Remove them from the
# cleaned data.
del cleaned_data["cc_myself"]
del cleaned_data["subject"]
# Always return the full collection of cleaned data.
return cleaned_data
为您的代码:
class ModelForm(forms.ModelForm):
# ...
def clean(self):
cleaned_data = self.cleaned_data
end_date = cleaned_data.get('end_date')
start_date = cleaned_data.get('start_date')
if end_date and start_date:
if end_date < start_date:
msg = 'Event end date should not occur before start date.'
self._errors['end_date'] = self.error_class([msg])
del cleaned_data['end_date']
return cleaned_data
这篇关于Django的。在自定义clean()方法中为Form.errors添加一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文