django将网络中的图片,保存成model中的ImageField的实例

(编辑:jimmy 日期: 2024/9/26 浏览:2)

有这样的情形,django个人头像在model中是:

class UserProfile(AbstractUser):
 """
 用户
 """
 name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
 image = models.ImageField(max_length=1000,upload_to='avatar/%Y/%m/', verbose_name=u'头像', null=True, blank=True)

正常情况下,需要客户端(app或者浏览器post上来图片,然后保存到image中)

例如:

image = request.data.get('image', None)
...
user.image=image
user.save()

但是,有这样的情况,如果是第三方,例如微博登录,前端通过微博接口获取到微博头像,post上来的就是头像的地址,https://xxx.xxx.jpg

这个时候如何通过图片url,保存到django的model中呢?

思路是,先通过url下载图片,然后保存

from django.core.files import File
from io import BytesIO
from urllib.request import urlopen
 
url = request.data.get('image', None)
r = urlopen(url)
io = BytesIO(r.read())
user.image.save("{}_{}.jpg".format(user.id,int(time.time())), File(io))

以上这篇django将网络中的图片,保存成model中的ImageField的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。