以编程方式将图像保存到 Django ImageField [英] Programmatically saving image to Django ImageField

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

问题描述

好的,我已经尝试了几乎所有的东西,但我无法让它工作.

Ok, I've tried about near everything and I cannot get this to work.

  • 我有一个带有 ImageField 的 Django 模型
  • 我有通过 HTTP 下载图像的代码(经过测试并有效)
  • 图像直接保存到upload_to"文件夹中(upload_to 是在 ImageField 上设置的那个)
  • 我需要做的就是将已经存在的图像文件路径与 ImageField 相关联

我用 6 种不同的方式编写了这段代码.

I've written this code about 6 different ways.

我遇到的问题是我正在编写的所有代码都会导致以下行为:(1) Django 将创建第二个文件,(2) 重命名新文件,在文件名的末尾添加一个 _,然后 (3) 不传输任何数据,基本上保留一个空的重命名文件.'upload_to'路径中剩下2个文件,一个是实际图片,一个是图片名称,但是是空的,当然ImageField路径设置为Django尝试创建的空文件.

The problem I'm running into is all of the code that I'm writing results in the following behavior: (1) Django will make a 2nd file, (2) rename the new file, adding an _ to the end of the file name, then (3) not transfer any of the data over leaving it basically an empty re-named file. What's left in the 'upload_to' path is 2 files, one that is the actual image, and one that is the name of the image,but is empty, and of course the ImageField path is set to the empty file that Django try to create.

如果不清楚,我会尝试说明:

In case that was unclear, I'll try to illustrate:

## Image generation code runs.... 
/Upload
     generated_image.jpg     4kb

## Attempt to set the ImageField path...
/Upload
     generated_image.jpg     4kb
     generated_image_.jpg    0kb

ImageField.Path = /Upload/generated_image_.jpg

如何在不让 Django 尝试重新存储文件的情况下执行此操作?我真正想要的是这种效果......

How can I do this without having Django try to re-store the file? What I'd really like is something to this effect...

model.ImageField.path = generated_image_path

...但这当然行不通.

...but of course that doesn't work.

是的,我已经在这里解决了其他问题,例如这个 以及 文件

And yes I've gone through the other questions here like this one as well as the django doc on File

更新经过进一步测试,它仅在 Windows Server 上的 Apache 下运行时才会出现此行为.在 XP 上的runserver"下运行时,它不会执行此行为.

UPDATE After further testing, it only does this behavior when running under Apache on Windows Server. While running under the 'runserver' on XP it does not execute this behavior.

我被难住了.

这是在XP上成功运行的代码...

Here is the code which runs successfully on XP...

f = open(thumb_path, 'r')
model.thumbnail = File(f)
model.save()

推荐答案

我有一些代码可以从网络上获取图像并将其存储在模型中.重要的部分是:

I have some code that fetches an image off the web and stores it in a model. The important bits are:

from django.core.files import File  # you need this somewhere
import urllib


# The following actually resides in a method of my model

result = urllib.urlretrieve(image_url) # image_url is a URL to an image

# self.photo is the ImageField
self.photo.save(
    os.path.basename(self.url),
    File(open(result[0], 'rb'))
    )

self.save()

这有点令人困惑,因为它脱离了我的模型并且有点脱离了上下文,但重要的部分是:

That's a bit confusing because it's pulled out of my model and a bit out of context, but the important parts are:

  • 从网络上提取的图像存储在upload_to文件夹中,而是由urllib.urlretrieve()存储为临时文件,然后被丢弃.
  • ImageField.save() 方法接受一个文件名(os.path.basename 位)和一个 django.core.files.File 对象.
  • The image pulled from the web is not stored in the upload_to folder, it is instead stored as a tempfile by urllib.urlretrieve() and later discarded.
  • The ImageField.save() method takes a filename (the os.path.basename bit) and a django.core.files.File object.

如果您有任何疑问或需要澄清,请告诉我.

Let me know if you have questions or need clarification.

为了清楚起见,这里是模型(减去任何必需的导入语句):

for the sake of clarity, here is the model (minus any required import statements):

class CachedImage(models.Model):
    url = models.CharField(max_length=255, unique=True)
    photo = models.ImageField(upload_to=photo_path, blank=True)

    def cache(self):
        """Store image locally if we have a URL"""

        if self.url and not self.photo:
            result = urllib.urlretrieve(self.url)
            self.photo.save(
                    os.path.basename(self.url),
                    File(open(result[0], 'rb'))
                    )
            self.save()

这篇关于以编程方式将图像保存到 Django ImageField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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