django admin 自定义表单验证

django admin custom form validation

我正在尝试使用表单验证在 django admin 中验证图像。

models.py

class website_index(models.Model):
  screenshot=models.ImageField(storage=AzureStorage(container="media"),upload_to='search/resources/screenshots/',blank=True,null=True)

admin.py

class CustomIndexModelForm(forms.ModelForm):
    class Meta:
        model = website_index
        fields = '__all__'

    def clean_image(self):
        screenshot = self.cleaned_data.get['screenshot']
        if screenshot:    
            w, h = get_image_dimensions(screenshot)
            if w!=h :
                raise forms.ValidationError('Upload a square image')
        return screenshot

    def __init__(self, *args, **kwargs):
        super(CustomIndexModelForm, self).__init__(*args, **kwargs)
        self.fields['parent_id'].queryset = cat_tree.objects.exclude(level=0)

class website_index_Admin(admin.ModelAdmin):
    form = CustomIndexModelForm 

我看到了其他答案,我确保这些点,当我上传违反验证规则的图像时,django 仍然没有引发任何验证错误。

字段名称是screenshotclean_image 永远不会被执行。您需要将方法名称更改为 clean_screenshot.