将文件从URLField保存到ImageField

时间:2017-04-09 12:25:44

标签: django python-3.x

我正在尝试从URLField下载我的文件并将其下载到ImageField。我得到的是错误

 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

Unicode error hint

The string that could not be encoded/decoded was: �PNG

模型:

image = models.ImageField(upload_to='posts/', blank=True)
image_url = models.URLField(null=True, blank=True)

def save(self, *args, **kwargs):
    if self.image_url:
        result = urllib.request.urlretrieve(self.image_url)
        self.image_url = ''
        self.image.save(
            os.path.basename(self.image_url),
            File(open(result[0]))
        )
    super(Post, self).save()

1 个答案:

答案 0 :(得分:0)

试试这个

File(open(result[0], 'rb'))