不属于表单一部分的字段的PerfomDjango验证



我想根据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的文档中,我发现在保存模型时不会自动应用验证器。它将我重定向到这个页面,但我真的不知道如何应用这些。知道吗?

下面是一个表单的示例,该表单在Model之外有这样一个自定义字段:

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

最新更新