问题:以编程方式将图像保存到Django ImageField

好的,我已经尝试了几乎所有内容,但无法正常工作。

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

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

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

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

## 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尝试重新存储文件的情况下执行此操作?我真正想要的就是这种效果……

model.ImageField.path = generated_image_path

…但是那当然是行不通的。

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

更新 在进一步测试之后,仅当在Windows Server上的Apache下运行时,它才会执行此行为。在XP上的“ runserver”下运行时,它不会执行此行为。

我很沮丧

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

f = open(thumb_path, 'r')
model.thumbnail = File(f)
model.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()

回答 0

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

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

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

  • 从Web提取的图像存储在upload_to文件夹中,而是由urllib.urlretrieve()作为临时文件存储,之后被丢弃。
  • ImageField.save()方法采用文件名(os.path.basename位)和django.core.files.File对象。

让我知道您是否有疑问或需要澄清。

编辑:为清楚起见,这是模型(减去任何必需的import语句):

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

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:

  • 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], 'rb'))
                    )
            self.save()

回答 1

如果尚未创建模型,则超级简单:

首先,将您的图片文件复制到上传路径(在以下代码段中假定为‘path /’)。

其次,使用类似:

class Layout(models.Model):
    image = models.ImageField('img', upload_to='path/')

layout = Layout()
layout.image = "path/image.png"
layout.save()

在django 1.4中进行了测试和工作,它可能也适用于现有模型。

Super easy if model hasn’t been created yet:

First, copy your image file to the upload path (assumed = ‘path/’ in following snippet).

Second, use something like:

class Layout(models.Model):
    image = models.ImageField('img', upload_to='path/')

layout = Layout()
layout.image = "path/image.png"
layout.save()

tested and working in django 1.4, it might work also for an existing model.


回答 2

只是一点点。tvon答案有效,但是,如果您在Windows上工作,则可能需要open()使用'rb'。像这样:

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

否则您的文件将在第一个0x1A字节处被截断。

Just a little remark. tvon answer works but, if you’re working on windows, you probably want to open() the file with 'rb'. Like this:

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

or you’ll get your file truncated at the first 0x1A byte.


回答 3

这是一种效果很好的方法,它还允许您将文件转换为某种格式(以避免“无法将模式P编写为JPEG”错误):

import urllib2
from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO

def download_image(name, image, url):
    input_file = StringIO(urllib2.urlopen(url).read())
    output_file = StringIO()
    img = Image.open(input_file)
    if img.mode != "RGB":
        img = img.convert("RGB")
    img.save(output_file, "JPEG")
    image.save(name+".jpg", ContentFile(output_file.getvalue()), save=False)

其中image是django ImageField或your_model_instance.image,这里是一个用法示例:

p = ProfilePhoto(user=user)
download_image(str(user.id), p.image, image_url)
p.save()

希望这可以帮助

Here is a method that works well and allows you to convert the file to a certain format as well (to avoid “cannot write mode P as JPEG” error):

import urllib2
from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO

def download_image(name, image, url):
    input_file = StringIO(urllib2.urlopen(url).read())
    output_file = StringIO()
    img = Image.open(input_file)
    if img.mode != "RGB":
        img = img.convert("RGB")
    img.save(output_file, "JPEG")
    image.save(name+".jpg", ContentFile(output_file.getvalue()), save=False)

where image is the django ImageField or your_model_instance.image here is a usage example:

p = ProfilePhoto(user=user)
download_image(str(user.id), p.image, image_url)
p.save()

Hope this helps


回答 4

好的,如果您需要做的只是将现有图像文件路径与ImageField相关联,那么此解决方案可能会有所帮助:

from django.core.files.base import ContentFile

with open('/path/to/already/existing/file') as f:
  data = f.read()

# obj.image is the ImageField
obj.image.save('imgfilename.jpg', ContentFile(data))

好吧,如果认真的话,已经存在的图像文件将不会与ImageField关联,但是该文件的副本将在upload_to dir中创建为“ imgfilename.jpg”,并将与ImageField关联。

Ok, If all you need to do is associate the already existing image file path with the ImageField, then this solution may be helpfull:

from django.core.files.base import ContentFile

with open('/path/to/already/existing/file') as f:
  data = f.read()

# obj.image is the ImageField
obj.image.save('imgfilename.jpg', ContentFile(data))

Well, if be earnest, the already existing image file will not be associated with the ImageField, but the copy of this file will be created in upload_to dir as ‘imgfilename.jpg’ and will be associated with the ImageField.


回答 5

我所做的是创建自己的存储,该存储不会将文件保存到磁盘:

from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):

    def _open(self, name, mode='rb'):
        return File(open(self.path(name), mode))

    def _save(self, name, content):
        # here, you should implement how the file is to be saved
        # like on other machines or something, and return the name of the file.
        # In our case, we just return the name, and disable any kind of save
        return name

    def get_available_name(self, name):
        return name

然后,在我的模型中,对于我的ImageField,我使用了新的自定义存储:

from custom_storage import CustomStorage

custom_store = CustomStorage()

class Image(models.Model):
    thumb = models.ImageField(storage=custom_store, upload_to='/some/path')

What I did was to create my own storage that will just not save the file to the disk:

from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):

    def _open(self, name, mode='rb'):
        return File(open(self.path(name), mode))

    def _save(self, name, content):
        # here, you should implement how the file is to be saved
        # like on other machines or something, and return the name of the file.
        # In our case, we just return the name, and disable any kind of save
        return name

    def get_available_name(self, name):
        return name

Then, in my models, for my ImageField, I’ve used the new custom storage:

from custom_storage import CustomStorage

custom_store = CustomStorage()

class Image(models.Model):
    thumb = models.ImageField(storage=custom_store, upload_to='/some/path')

回答 6

如果您只想“设置”实际的文件名,而又不会导致加载和重新保存文件(!!)或使用charfield(!!!)的开销,那么您可能想尝试这样的方法- —

model_instance.myfile = model_instance.myfile.field.attr_class(model_instance, model_instance.myfile.field, 'my-filename.jpg')

它将照亮您的model_instance.myfile.url及其所有其他内容,就像您实际上已上传文件一样。

就像@ t-stone所说的,我们真正想要的是能够设置instance.myfile.path =’my-filename.jpg’,但是Django目前不支持。

If you want to just “set” the actual filename, without incurring the overhead of loading and re-saving the file (!!), or resorting to using a charfield (!!!), you might want to try something like this —

model_instance.myfile = model_instance.myfile.field.attr_class(model_instance, model_instance.myfile.field, 'my-filename.jpg')

This will light up your model_instance.myfile.url and all the rest of them just as if you’d actually uploaded the file.

Like @t-stone says, what we really want, is to be able to set instance.myfile.path = ‘my-filename.jpg’, but Django doesn’t currently support that.


回答 7

我认为这是最简单的解决方案:

from django.core.files import File

with open('path_to_file', 'r') as f:   # use 'rb' mode for python3
    data = File(f)
    model.image.save('filename', data, True)

THe simplest solution in my opinion:

from django.core.files import File

with open('path_to_file', 'r') as f:   # use 'rb' mode for python3
    data = File(f)
    model.image.save('filename', data, True)

回答 8

这些答案很多都已经过时了,我花了很多时间感到沮丧(对于Django和Web开发人员来说,我一般都是新手)。但是,我通过@iambibhas找到了这个出色的要点:https ://gist.github.com/iambibhas/5051911

import requests

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


def save_image_from_url(model, url):
    r = requests.get(url)

    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(r.content)
    img_temp.flush()

    model.image.save("image.jpg", File(img_temp), save=True)

A lot of these answers were outdated, and I spent many hours in frustration (I’m fairly new to Django & web dev in general). However, I found this excellent gist by @iambibhas: https://gist.github.com/iambibhas/5051911

import requests

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


def save_image_from_url(model, url):
    r = requests.get(url)

    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(r.content)
    img_temp.flush()

    model.image.save("image.jpg", File(img_temp), save=True)


回答 9

这可能不是您要寻找的答案。但是您可以使用charfield而不是ImageFile来存储文件的路径。这样,您可以以编程方式将上载的图像与字段相关联,而无需重新创建文件。

This is might not be the answer you are looking for. but you can use charfield to store the path of the file instead of ImageFile. In that way you can programmatically associate uploaded image to field without recreating the file.


回答 10

你可以试试:

model.ImageField.path = os.path.join('/Upload', generated_image_path)

You can try:

model.ImageField.path = os.path.join('/Upload', generated_image_path)

回答 11

class tweet_photos(models.Model):
upload_path='absolute path'
image=models.ImageField(upload_to=upload_path)
image_url = models.URLField(null=True, blank=True)
def save(self, *args, **kwargs):
    if self.image_url:
        import urllib, os
        from urlparse import urlparse
        file_save_dir = self.upload_path
        filename = urlparse(self.image_url).path.split('/')[-1]
        urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
        self.image = os.path.join(file_save_dir, filename)
        self.image_url = ''
    super(tweet_photos, self).save()
class tweet_photos(models.Model):
upload_path='absolute path'
image=models.ImageField(upload_to=upload_path)
image_url = models.URLField(null=True, blank=True)
def save(self, *args, **kwargs):
    if self.image_url:
        import urllib, os
        from urlparse import urlparse
        file_save_dir = self.upload_path
        filename = urlparse(self.image_url).path.split('/')[-1]
        urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
        self.image = os.path.join(file_save_dir, filename)
        self.image_url = ''
    super(tweet_photos, self).save()

回答 12

class Pin(models.Model):
    """Pin Class"""
    image_link = models.CharField(max_length=255, null=True, blank=True)
    image = models.ImageField(upload_to='images/', blank=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    source_name = models.CharField(max_length=255, null=True, blank=True)
    source_link = models.CharField(max_length=255, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tags = models.ForeignKey(Tag, blank=True, null=True)

    def __unicode__(self):
        """Unicode class."""
        return unicode(self.image_link)

    def save(self, *args, **kwargs):
        """Store image locally if we have a URL"""
        if self.image_link and not self.image:
            result = urllib.urlretrieve(self.image_link)
            self.image.save(os.path.basename(self.image_link), File(open(result[0], 'r')))
            self.save()
            super(Pin, self).save()
class Pin(models.Model):
    """Pin Class"""
    image_link = models.CharField(max_length=255, null=True, blank=True)
    image = models.ImageField(upload_to='images/', blank=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    source_name = models.CharField(max_length=255, null=True, blank=True)
    source_link = models.CharField(max_length=255, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tags = models.ForeignKey(Tag, blank=True, null=True)

    def __unicode__(self):
        """Unicode class."""
        return unicode(self.image_link)

    def save(self, *args, **kwargs):
        """Store image locally if we have a URL"""
        if self.image_link and not self.image:
            result = urllib.urlretrieve(self.image_link)
            self.image.save(os.path.basename(self.image_link), File(open(result[0], 'r')))
            self.save()
            super(Pin, self).save()

回答 13

加工!您可以使用FileSystemStorage保存图像。检查下面的例子

def upload_pic(request):
if request.method == 'POST' and request.FILES['photo']:
    photo = request.FILES['photo']
    name = request.FILES['photo'].name
    fs = FileSystemStorage()
##### you can update file saving location too by adding line below #####
    fs.base_location = fs.base_location+'/company_coverphotos'
##################
    filename = fs.save(name, photo)
    uploaded_file_url = fs.url(filename)+'/company_coverphotos'
    Profile.objects.filter(user=request.user).update(photo=photo)

Working! You can save image by using FileSystemStorage. check the example below

def upload_pic(request):
if request.method == 'POST' and request.FILES['photo']:
    photo = request.FILES['photo']
    name = request.FILES['photo'].name
    fs = FileSystemStorage()
##### you can update file saving location too by adding line below #####
    fs.base_location = fs.base_location+'/company_coverphotos'
##################
    filename = fs.save(name, photo)
    uploaded_file_url = fs.url(filename)+'/company_coverphotos'
    Profile.objects.filter(user=request.user).update(photo=photo)

回答 14

您可以使用Django REST框架和python Requests库以编程方式将图像保存到Django ImageField

这是一个例子:

import requests


def upload_image():
    # PATH TO DJANGO REST API
    url = "http://127.0.0.1:8080/api/gallery/"

    # MODEL FIELDS DATA
    data = {'first_name': "Rajiv", 'last_name': "Sharma"}

    #  UPLOAD FILES THROUGH REST API
    photo = open('/path/to/photo'), 'rb')
    resume = open('/path/to/resume'), 'rb')
    files = {'photo': photo, 'resume': resume}

    request = requests.post(url, data=data, files=files)
    print(request.status_code, request.reason) 

Your can use Django REST framework and python Requests library to Programmatically saving image to Django ImageField

Here is a Example:

import requests


def upload_image():
    # PATH TO DJANGO REST API
    url = "http://127.0.0.1:8080/api/gallery/"

    # MODEL FIELDS DATA
    data = {'first_name': "Rajiv", 'last_name': "Sharma"}

    #  UPLOAD FILES THROUGH REST API
    photo = open('/path/to/photo'), 'rb')
    resume = open('/path/to/resume'), 'rb')
    files = {'photo': photo, 'resume': resume}

    request = requests.post(url, data=data, files=files)
    print(request.status_code, request.reason) 

回答 15

在Django 3中,具有这样的模型:

class Item(models.Model):
   name = models.CharField(max_length=255, unique=True)
   photo= models.ImageField(upload_to='image_folder/', blank=True)

如果图片已经上传,我们可以直接做:

Item.objects.filter(...).update(photo='image_folder/sample_photo.png')

要么

my_item = Item.objects.get(id=5)
my_item.photo='image_folder/sample_photo.png'
my_item.save()

With Django 3, with a model such as this one:

class Item(models.Model):
   name = models.CharField(max_length=255, unique=True)
   photo= models.ImageField(upload_to='image_folder/', blank=True)

if the image has already been uploaded, we can directly do :

Item.objects.filter(...).update(photo='image_folder/sample_photo.png')

or

my_item = Item.objects.get(id=5)
my_item.photo='image_folder/sample_photo.png'
my_item.save()

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。