我正在尝试使用表单验证在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仍未提出任何验证错误。
答案 0 :(得分:5)
字段名称为屏幕截图。 clean_image 永远不会被执行。您需要将方法名称更改为 clean_screenshot 。