【问题标题】:django. adding a field to Form.errors in a custom clean() methoddjango。在自定义 clean() 方法中将字段添加到 Form.errors
【发布时间】:2011-04-04 06:43:08
【问题描述】:

我有一个事件模型,我想在模型上的自定义 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 字段,以某种方式将其命名为有错误的字段。否则,我只会收到更改表单顶部出现的错误消息。

【问题讨论】:

    标签: django-models django-admin validation


    【解决方案1】:

    从 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
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 啊,我明白了。我将clean() 方法直接应用于模型。那么这需要发生在 ModelAdmin 使用的表单上吗?
      • @Daryl docs.djangoproject.com/en/dev/ref/contrib/admin/… 可能会帮助你。另一方面,您的答案接受度很低。如果您在一般问题上需要更多帮助,您可能需要解决这个问题。
      • @Daryl docs.djangoproject.com/en/dev/ref/models/instances/… 是另一个部分,如果您想进行模型级验证,您可能会感兴趣。 Model.clean_fields 特别是。
      • 我投了反对票,因为当我看到对_errors 的直接访问时,我的眼睛燃烧了。
      猜你喜欢
      • 2016-01-19
      • 2011-02-25
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 2014-04-02
      相关资源
      最近更新 更多