违规代码:
file_name = os.path.basename(image_url)
downloaded = urllib2.urlopen(image_url).read()
image_file = File(downloaded, name=file_name)
image_file.size = len( downloaded )
model = BlogPost()
model.image.save(file_name, image_file)
model.save()
模型:
class BlogPost(models.Model):image = models.ImageField(upload_to ='blog-image',help_text ='Feature image',blank = True,null = True)
我明白这个:
AttributeError: 'str' object has no attribute 'read'
如果我删除了行image_file.size:
AttributeError: 'str' object has no attribute 'name'
downloaded
已填充,因此已成功下载该文件 .
我究竟做错了什么?
1 回答
问题是文件需要的不仅仅是内容 . 而不是尝试使用
File
并执行此操作:我应该使用ContentFile并执行此操作:
来自documentation: