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

yipeiwu_com6年前Python基础

有这样的情形,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上来的就是头像的地址,/zb_users/upload/202003/q14cwovkyok.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的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

TensorFlow数据输入的方法示例

TensorFlow数据输入的方法示例

读取数据(Reading data) TensorFlow输入数据的方式有四种: tf.data API:可以很容易的构建一个复杂的输入通道(pipeline)(首选数据输入方式...

python matplotlib绘图,修改坐标轴刻度为文字的实例

python matplotlib绘图,修改坐标轴刻度为文字的实例

工作中偶尔需要做客流分析,用pyplot 库绘图。一般情况下, x 轴刻度默认显示为数字。 例如: 我希望x 轴刻度显示为星期日期。 查询pyplot 文档, 发现了 xtick()...

python3实现elasticsearch批量更新数据

废话不多说,直接上代码! updateBody = { "query":{ "range":{ "write_date": { "g...

python实现RSA加密(解密)算法

python实现RSA加密(解密)算法

RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。 今天只有短的RSA钥匙才可能被强力方式解破。到2008年为止,世界上...

Python3.6实现带有简单界面的有道翻译小程序

本人使用的是Python3.6(32bit),在win10上运行的     代码如下: from tkinter import * import url...