django admin ModelForm field 验证

孟品
2023-12-01

继承ModelForm

覆盖 clean_field_name(self)方法

class YourModelForm(ModelForm):
    def clean_field_name(self):
        data = self.cleaned_data['field_name']
        if not data:  # 如果data不满足满足条件
            raise forms.ValidationError('data is invalid')
        return data

    class Meta:
        model = YourModel
        fields = '__all__'

在ModelAdmin指定form

class YourModelAdmin(models.ModelAdmin):
    form = YourModelForm
 类似资料: