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

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

问题描述




  • 我有一个带有ImageField的Django模型

  • 我有通过HTTP下载图像的代码(测试和工作)

  • 图像直接保存到'upload_to'文件夹upload_to是ImageField上设置的一个)

  • 我需要做的是将现有的图像文件路径与ImageField



我已经编写了6种不同的方法。



我遇到的问题是所有的代码我写的结果如下:
(1)Django将会创建一个第二个文件,(2)重新命名新的文件,将_添加到文件名的末尾,然后(3)不传输任何离开它的数据基本上都是一个空的重新命名的文件。 'upload_to'路径中剩下的是2个文件,一个是实际图像,一个是图像的名称,但是为空,当然,ImageField路径设置为Django尝试创建的空文件



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

  ##图像生成代码运行.... 
/上传
generated_image.jpg 4kb

##尝试设置ImageField路径...
/上传
generated_image.jpg 4kb
generated_image_.jpg 0kb

ImageField.Path = /Upload/generated_image_.jpg

如果没有Django尝试重新存储文件,我该怎么做?我真正想要的是这样的东西...

  model.ImageField.path = generated_image_path 

...但当然不起作用。



是的,我已经经历了其他问题,如这一个以及文件



更新
进一步测试后,只有在Windows Server上的Apache下运行时,才会出现此问题。在XP下的runserver下运行时,它不会执行此行为。



我被骗了



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

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


解决方案

我有一些代码可以从网络并将其存储在模型中。重要的是:

 从django.core.files导入文件#你需要这个地方
import urllib


#以下实际上驻留在我的模型的一个方法

result = urllib.urlretrieve(image_url)#image_url是图像的URL

#self.photo是ImageField
self.photo.save(
os.path.basename(self.url),
File(open(result [0]))


self.save()

这有点混乱因为它被拉出我的模型,有点不在上下文中,但重要的部分是:




  • 从网络拉出的图像是 not 存储在upload_to文件夹中,它被urllib.urlretrieve()存储为tempfile,稍后被丢弃。

  • ImageField.save()方法需要一个filename(os.path.basename位)和django.core.files.File对象。



让我知道,如果你有问题或需要澄清



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

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

def cache(self):
如果我们有一个URL,请在本地存储图像

如果self.url和不是self.photo:
result = urllib.urlretrieve(self.url)
self.photo.save(
os.path.basename(self.url),
File( open(result [0]))

self.save()


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

  • I have a Django model with an ImageField on it
  • I have code that downloads an image via HTTP (tested and works)
  • The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the ImageField)
  • All I need to do is associate the already existing image file path with the ImageField

I've written this code about 6 different ways.

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

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

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.

I am stumped.

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]))
    )

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:

  • 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.

Edit: 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]))
                    )
            self.save()

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

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