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设计】。

相关文章

python 重命名轴索引的方法

如下所示: import numpy as np from pandas import Series, DataFrame ###重命名轴索引 data = DataFrame(np...

python 实现list或string按指定分段

我就废话不多说了,直接上代码吧! #方法一 def list_cut(mylist,count): length=len(mylist) merchant=length//c...

对python操作kafka写入json数据的简单demo分享

如下所示: 安装kafka支持库pip install kafka-python from kafka import KafkaProducer import json...

CentOS7.3编译安装Python3.6.2的方法

CentOS7.3编译安装Python3.6.2的方法

我使用的是 CentOS7.3 安装 Python3.6.2 1.查看是否已经安装Python Centos7 默认安装了Python2.7.5 因为一些命令要用它比如 yum 它使用...

Python判断Abundant Number的方法

本文实例讲述了Python判断Abundant Number的方法。分享给大家供大家参考。具体如下: Abundant Number,中文译成:盈数(又称 丰数, 过剩数abundant...