栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

以编程方式将图像保存到Django ImageField

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

以编程方式将图像保存到Django ImageField

我有一些代码可以从网络上获取图像并将其存储在模型中。重要的位是:

from django.core.files import File  # you need this somewhereimport urllib# The following actually resides in a method of my modelresult = urllib.urlretrieve(image_url) # image_url is a URL to an image# self.photo is the ImageFieldself.photo.save(    os.path.basename(self.url),    File(open(result[0], 'rb'))    )self.save()

这有点令人困惑,因为它脱离了我的模型并且脱离了上下文,但是重要的部分是:

  • 从Web提取的图像未存储在upload_to文件夹中,而是由urllib.urlretrieve()作为临时文件存储,之后被丢弃。
  • ImageField.save()方法采用文件名(os.path.basename位)和django.core.files.File对象。
    让我知道你是否有疑问或需要澄清。

编辑:为清楚起见,这里是模型(减去任何必需的import语句):

class CachedImage(models.Model):    url = models.CharField(max_length=255, unique=True)    photo = models.ImageField(upload_to=photo_path, blank=True)    def cache(self):        """Store image locally if we have a URL"""        if self.url and not self.photo: result = urllib.urlretrieve(self.url) self.photo.save(         os.path.basename(self.url),         File(open(result[0], 'rb'))         ) self.save()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/375074.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号