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

发布于 2024-10-30 16:00:36 字数 457 浏览 3 评论 0原文

我有一个事件模型,我想在模型上的自定义 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.')

效果很好,只是我想通过以某种方式将其指定为有错误的字段,突出显示管理 UI 中的 self.end_date 字段。否则,我只会收到更改表单顶部出现的错误消息。

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.')

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丑疤怪 2024-11-06 16:00:36

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

表单.add_error('field_name', 'error_msg 或 ValidationError 实例')
如果 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

From Django 1.7 you can directly add error to the particular field by using add_error method. Django docs

form.add_error('field_name', 'error_msg or ValidationError instance')
If the field_name is None the error will be added to 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
看透却不说透 2024-11-06 16:00:36

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

The docs explain how to do this at the bottom.

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

for your code:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文