Python 如何将图像从URL下载到django?

Python 如何将图像从URL下载到django?,python,python-3.x,django,django-models,django-forms,Python,Python 3.x,Django,Django Models,Django Forms,我想通过URL加载图像,但只有URL本身保存到模型中,如何指定保存到媒体文件夹的路径,以及如何保存它 from django.db import models import urllib.request from urllib.parse import urlparse upload_path = 'media/' class Image(models.Model): image = models.ImageField(upload_to=upload_path, null= Tru

我想通过URL加载图像,但只有URL本身保存到模型中,如何指定保存到媒体文件夹的路径,以及如何保存它

from django.db import models
import urllib.request
from urllib.parse import urlparse

upload_path = 'media/'

class Image(models.Model):
    image = models.ImageField(upload_to=upload_path, null= True, blank=True)
    image_url = models.URLField(blank=True, null=True)

    def get_image(self):
        name = urlparse(str(self.image)).path.split('/')[-1]
        urllib.request.urlretrieve(str(self.image_url), 'img\media\media' + name + '.jpg')

您可以下载给定URL的图像,然后通过
NamedTemporaryFile
上传它:

from urllib.request
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile

class Image(models.Model):
    image = models.ImageField(upload_to=upload_path, null= True, blank=True)
    image_url = models.URLField(blank=True, null=True)
    
    def get_image(self, url):
       img_tmp = NamedTemporaryFile(delete=True)
       with urlopen() as uo:
           assert uo.status == 200
           img_tmp.write(uo.read())
           img_tmp.flush()
       img = File(img_tmp)
       self.image.save('image.jpeg', img)
       self.image_url = url
因此,您可以通过以下方式制作图像:

my_img = Image()
my_img.get_image('http://i.stack.imgur.com/PIFN0.jpg')
my_img.save()

不,不仅URL保存到模型中。
ImageField
保存文件路径,并将对象保存在
MEDIA\u ROOT
中。但是这确实不起作用,因为你基本上要求下载一个已经在你的媒体目录中的文件。@messageman上传一个代码截图通常是不好的。相反,您应该将代码复制/粘贴到问题中。在前面使用4个空格将其格式化为代码。这将允许搜索引擎根据代码编制索引,并允许其他人复制/粘贴您的代码。请更新您的问题。函数的签名看起来不正常。通常,它应该使用一个参数
url
,该参数指定从何处获取项目。通过使用
image.url
,您可以获得已经存在的图像的url(如果存在),因此在最好的情况下,您可以从自己的Web服务器下载图像。@J'e上载到pastebin@WillemVanOnsem那我该怎么办?你能告诉我吗?