【发布时间】:2018-06-04 22:54:09
【问题描述】:
在项目中有以下规则:图像字段是可选的,默认图像是用户不知情的情况。图片由用户在 django 中发送,并且必须具有尺寸(宽度> = 900,高度> = 400)。
我正在尝试验证 admin.py 中的尺寸,但是当我在 imagefield 中有默认参数时尝试注册时会出现问题。
即使在目录中,也会出现未找到的图像错误。没有 admin.py 中的验证功能,它可以正常工作。
models.py
class Event(models.Model):
banner = models.ImageField('banner', upload_to='events/banners', default='events/banners/banner_padrao_eventos.png', blank=True)
admin.py
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = '__all__'
def clean_banner(self):
banner = self.cleaned_data.get('banner')
if banner:
img = Image.open(banner)
width, height = img.size
max_width = 900
max_height = 400
if width < max_width or height < max_height:
raise forms.ValidationError(
'Image is incorrectly sized:% s x% s pixels. Please insert an image with% s x% s pixels.'
% (width, height, max_width, max_height))
if len(banner) > (3 * 1024 * 1024):
raise forms.ValidationError('Very large image file (maximum of 3MB).')
name_img, ext = banner.name.split('.')
if not (ext.lower() in ['png', 'jpg', 'jpeg']):
raise forms.ValidationError('Please use the image in JPG, JPEG or PNG format.')
else:
raise forms.ValidationError('The loaded image could not be read.')
return banner
如何使默认图像在验证中被考虑?
【问题讨论】:
标签: python django django-models