【问题标题】:Perfom Django Validation for field that is NOT part of form对不属于表单的字段执行 Django 验证
【发布时间】:2021-01-02 04:19:00
【问题描述】:

我想根据我的 Django 模型中的一个字段引发 ValidationError,而不是将相应的字段作为 ModelForm 的一部分。我在谷歌上搜索了一下后发现了模型验证器的概念。所以我尝试执行以下操作:

def minimumDuration(value):
    if value == 0:
        raise ValidationError("Minimum value accepted is 1 second!")

class PlaylistItem(models.Model):
    position = models.IntegerField(null=False)
    content = models.ForeignKey(Content, null=True, on_delete=models.SET_NULL)
    item_duration = models.IntegerField(validators = [minimumDuration], default = 5, null=True, blank=True)
    playlist = models.ForeignKey(Playlist, null=True, on_delete=models.CASCADE)

但是,当我在相应字段中引入 0 时,不会出现错误。从 Django 的文档中,我发现保存模型时不会自动应用验证器。它把我重定向到this page,但我真的不明白如何应用这些。有什么想法吗?

【问题讨论】:

  • 那么究竟是什么不清楚,你尝试了什么
  • 有一种名为ModelForm的表单,它将表单中的数据保存到它所绑定的模型的数据库表中。验证仅在您使用表单时有效。

标签: python django django-models validationerror django-model-field


【解决方案1】:

这是一个在模型之外具有此类自定义字段的表单示例:

class ExampleForm(forms.ModelForm):
    custom_field = forms.BooleanField(
        label='Just non model field, replace with the type you need',
        required=False
    )

    class Meta:
        model = YourModel

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # optional: further customize field widget
        self.fields['custom_field'].widget.attrs.update({
            'id': self.instance.pk + '-custom_field',
            'class': 'custom-field-class'
        })
        self.fields['custom_field'].initial = self._get_custom_initial()

    def _get_custom_initial(self):
        # compute initial value based on self.instance and other logic
        return True

    def _valid_custom_field(value):
        # validate your value here
        # return Boolean

    def clean(self):
        """
        The important method: override clean to hook your validation
        """
        super().clean()
        custom_field_val = self.cleaned_data.get('custom_field')
        if not self._valid_custom_field(custom_field_val):
            raise ValidationError(
                'Custom Field is not valid')

【讨论】:

  • 我需要它。不在表单中但在模型中的字段。我认为必须有 1-2 行的方式来进行验证,但我最终做的是在 views.py 中编写自己的验证函数。但是,我感谢您的详细回答,如果我最终处于相反的情况,我一定会使用它,哈哈。谢谢!
  • 但是你为什么不将它包含在表单中并在那里进行验证:)(类似于模型验证)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 2016-04-29
  • 2019-08-25
  • 2015-06-25
相关资源
最近更新 更多