Django验证ImageField维度等
发布时间:2020-11-18 00:03:21 所属栏目:Python 来源:互联网
导读:我有一个自定义清洁方法如下: def clean_image(self): image = self.cleaned_data[image] if image: from django.core.files.images import get_image_dimensions w, h = get_image_dimensions(image)
|
我有一个自定义清洁方法如下: def clean_image(self):
image = self.cleaned_data['image']
if image:
from django.core.files.images import get_image_dimensions
w,h = get_image_dimensions(image)
if not image.content_type in settings.VALID_IMAGE_FORMATS:
raise forms.ValidationError(u'Only *.gif,*.jpg and *.png images are allowed.')
if w > settings.VALID_IMAGE_WIDTH or h > settings.VALID_IMAGE_HEIGHT:
raise forms.ValidationError(u'That image is too big. The image needs to be ' + str(settings.VALID_IMAGE_WIDTH) + 'px * ' + str(settings.VALID_IMAGE_HEIGHT) + 'px (or less).')
return image
问题场景是这样的: 已上传图片.我现在想要使用ImageField小部件显示的复选框清除它.提交表格时,明确表示不清楚. 如果我删除自定义清理方法,则清除确实有效.因此我猜我的方法做错了. 解决方法当django实现这个验证时有3个问题:> Django需要获取这些字段的值,总是需要返回一个值 self.cleaned_data.get['image'] >代码如下所示: class Meta:
model = NameModel
def clean_image(self):
image = self.cleaned_data.get['image']
if image:
from django.core.files.images import get_image_dimensions
w,*.jpg and *.png images are allowed.')
if w > settings.VALID_IMAGE_WIDTH or h > settings.VALID_IMAGE_HEIGHT:
raise forms.ValidationError(u'That image is too big. The image needs to be ' + str(settings.VALID_IMAGE_WIDTH) + 'px * ' + str(settings.VALID_IMAGE_HEIGHT) + 'px (or less).')
return image (编辑:东莞站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 使用Python在OpenOffice / Microsoft Word中格式化输出
- 为什么python设计为str(无)返回’None’而不是空字符串?
- python – 将密码字段迁移到Django
- python – Pygraphviz / networkx设置节点级别或层
- 有没有办法让Django的USStateField()没有预先选择的值?
- python – 逐行文件处理,for-loop vs with
- python – “I; 16”图像文件的numpy.array
- python中的全局变量混淆
- `with canvas:`(Python`with something()as x:`)如何隐式
- python – 单元测试(烧瓶 – 静止)GET API调用时获得500内部
