Django 从 url 保存图像并与 ImageField 连接 [英] Django save image from url and connect with ImageField

查看:29
本文介绍了Django 从 url 保存图像并与 ImageField 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 models.py 中有:

class Item(models.Model):
    image_file = models.ImageField(upload_to='images')
    image_url = models.URLField()

我希望 django 自动从 image_url 下载和本地保存图像,并用 image_file

I want django automatically download and locally save image from image_url and "connect" it with image_file

它应该如何运作:

  1. 我粘贴https://docs.djangoproject.com/s/img/site/hdr_logo.gif进入管理中的 image_url 字段
  2. 点击保存"
  3. 在模板中写入.表明图片来自我的服务器,而不是 djangoproject.com
  1. I Paste https://docs.djangoproject.com/s/img/site/hdr_logo.gif into image_url field in admin
  2. Click "save"
  3. In templates write <img src="{{ item.image_file.url }}">. It shows image from my server, not djangoproject.com

我尝试过的:

我已经覆盖了 Item 类的 save 方法.我通过 urllib 在本地保存了图像,但我坚持将此保存的图像与 image_file 字段

I've overwritten save method of Item class. I saved image locally via urllib, but I am stuck on connecting this saved image with image_file field

推荐答案

from django.core.files import File
import os

class Item(models.Model):
    image_file = models.ImageField(upload_to='images')
    image_url = models.URLField()

...

def get_remote_image(self):
    if self.image_url and not self.image_file:
        result = urllib.urlretrieve(self.image_url)
        self.image_file.save(
                os.path.basename(self.image_url),
                File(open(result[0]))
                )
        self.save()

您可以覆盖默认的 save() 方法以自动调用 get_remote_image().

You can override the default save() method to automatically invoke get_remote_image().

参见:https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods

这篇关于Django 从 url 保存图像并与 ImageField 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆