如何从URL下载图像到django?

mes*_*man 1 python django django-models django-forms python-3.x

我想通过 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')
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

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

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

class ObjectWithImageField(models.Model):
    image = models.ImageField(upload_to=upload_path, null= True, blank=True)
    image_url = models.URLField(blank=True, null=True)
    
    def get_image_from_url(self, url):
       img_tmp = NamedTemporaryFile(delete=True)
       with urlopen(url) as uo:
           assert uo.status == 200
           img_tmp.write(uo.read())
           img_tmp.flush()
       img = File(img_tmp)
       self.image.save(img_tmp.name, img)
       self.image_url = url
Run Code Online (Sandbox Code Playgroud)

然后您可以使用以下命令制作图像:

my_obj = ObjectWithImageField()
my_obj.get_image_from_url('https://i.stack.imgur.com/PIFN0.jpg')
my_obj.save()
Run Code Online (Sandbox Code Playgroud)