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

Dar*_*ryl 8 validation django-models django-admin

我有一个事件模型,我想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.')
Run Code Online (Sandbox Code Playgroud)

哪个工作正常,除了我想self.end_date在管理界面中突出显示该字段,通过某种方式将其指定为有错误的字段.否则,我只会收到更改表单顶部发生的错误消息.

Mr.*_*fee 16

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

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
Run Code Online (Sandbox Code Playgroud)


DTi*_*ing 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
Run Code Online (Sandbox Code Playgroud)

为您的代码:

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
Run Code Online (Sandbox Code Playgroud)

  • 我投了反对票,因为当我看到直接访问 `_errors` 时,我的眼睛都烧了。 (2认同)