django admin ModelForm field 验证

继承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

你可能感兴趣的:(Django)