2011-12-30 50 views
1

违规代码:试图图像下载并保存到的ImageField失败

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() 

型号:

类博文(models.Model): 图像= models.ImageField(upload_to =”博客图像”, help_text = '特征图像', 空白=真, 空=真)

我得到这个:

AttributeError: 'str' object has no attribute 'read' 

如果我删除行image_file.size:

AttributeError: 'str' object has no attribute 'name' 

downloaded填充,因此它已成功下载的文件。

我在做什么错?

回答

1

问题在于文件需要的不仅仅是内容。而不是试图用File和这样做:

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

我应该使用ContentFile和做到这一点:

image_file = ContentFile(downloaded) 

documentation

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