首页 文章

尝试将图像下载并保存到ImageField失败

提问于
浏览
1

违规代码:

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 回答

  • 1

    问题是文件需要的不仅仅是内容 . 而不是尝试使用 File 并执行此操作:

    image_file = File(downloaded, name=file_name)
    image_file.size = len( downloaded )
    

    我应该使用ContentFile并执行此操作:

    image_file = ContentFile(downloaded)
    

    来自documentation

    ContentFile类继承自File,但与File不同,它对字符串内容而不是实际文件进行操作 .

相关问题