Django的。在自定义clean()方法中向Form.errors添加字段

时间:2011-04-04 06:43:09

标签: django-models django-admin validation

我有一个事件模型,我想在模型上的自定义def clean(self):方法中放置以下验证规则:

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字段,以某种方式将其指定为有错误的字段。否则,我只会收到更改表单顶部的错误消息。

2 个答案:

答案 0 :(得分:15)

从Django 1.7开始,您可以使用add_error方法直接向特定字段添加错误。 Django docs

form.add_error('field_name', 'error_msg or ValidationError instance') 如果field_nameNone,则错误将添加到non_field_errors

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:
            self.add_error('end_date', 'Event end date should not occur before start date.')
            # You can use ValidationError as well
            # self.add_error('end_date', form.ValidationError('Event end date should not occur before start date.'))

    return cleaned_data

答案 1 :(得分:13)

docs解释了如何在底部执行此操作。

提供示例:

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