我创建了文章创建表单。还有一个图片上传按钮。
我用枕头调整大小以上传图像。但是当我说保存表单而不上传图片时,会出现此错误;
clean_image中的forms.py,第19行 “ NoneType”对象没有属性“名称”
当我将图片与图片一起保存时,没有问题。但是没有图像我就无法保存。
怎么说,如果不上传任何图片“跳过此部分”(def clean_image(self):)” ?
forms.py
from django import forms
from .models import Article
from django.core.files.base import ContentFile
from django.utils.translation import ugettext_lazy as _
from PIL import Image
import hashlib
import io
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ["title", "content","image"]
def clean_image(self):
image = self.cleaned_data.get('image')
md5 = hashlib.md5()
md5.update(repr(image.name).encode('utf-8')) **#19.line is here!!!**
file_name = md5.hexdigest()
if image.size > 30 * 1024 * 1024:
raise forms.ValidationError(_('File is too big.'), code='invalid')
image = Image.open(image)
if image.size[0] < 600 or image.size[1] < 600:
raise forms.ValidationError(_('Your image needs to be at least 600x600.'))
if image.format not in ('BMP', 'PNG', 'JPEG', 'GIF'):
raise forms.ValidationError(_("Unsupported image type. Please uplod a bmp, png, jpeg, or gif."),
code='invalid')
image.thumbnail([1024, 1024], Image.ANTIALIAS)
image_io = io.BytesIO()
image.save(image_io, format=image.format)
image_name = '{}.{}'.format(file_name, image.format)
image = ContentFile(image_io.getvalue(), image_name)
return image
非常感谢您!
答案 0 :(得分:0)
在处理图像之前只需检查该字段是否为空:
def clean_image(self):
image = self.cleaned_data.get('image')
if image:
md5 = hashlib.md5()
# ... the rest of the image processing stuff goes here...
return image