好吧,我几乎什么都试过了,但我不能让它工作。

我有一个带有ImageField的Django模型 我有通过HTTP下载图像的代码(测试和工作) 图像直接保存到'upload_to'文件夹中(upload_to是在ImageField中设置的) 我所需要做的就是将已经存在的图像文件路径与ImageField关联起来

我用六种不同的方式写了这段代码。

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.

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

## 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 on File

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

我被难住了。

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

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

当前回答

如果模型还没有创建,超级简单:

首先,将图像文件复制到上传路径(在下面的代码片段中假设= 'path/')。

其次,使用如下语句:

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

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

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

其他回答

就说一点。答案是可行的,但是,如果你在windows上工作,你可能想用'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字节处被截断。

如果您只想“设置”实际的文件名,而不需要加载和重新保存文件(!!),或者使用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目前不支持这个功能。

class DemoImage(models.Model):
    title = models.TextField(max_length=255, blank=False)
    image = models.ImageField(blank=False, upload_to="images/DemoImages/")

import requests
import urllib.request
from django.core.files import File
url = "https://path/to/logo.jpg"

# Below 3 lines is to fake as browser agent 
# as many sites block urllib class suspecting to be bots
opener = urllib.request.build_opener()
opener.addheaders = [("User-agent", "Mozilla/5.0")]
urllib.request.install_opener(opener)

# Issue command to actually download and create temp img file in memory        
result = urllib.request.urlretrieve(url)

# DemoImage.objects.create(title="title", image=File(open(result[0], "rb"))) 
# ^^ This erroneously results in creating the file like 
# images/DemoImages/path/to/temp/dir/logo_image_file 
# as opposed to 
# images/DemoImages/logo_image_file

# Solution to get the file in images/DemoImages/
reopen = open(result[0], "rb") # Returns a BufferedReader object of the temp image
django_file = File(reopen)     # Create the file from the BufferedReader object 
demoimg = DemoImage()
demoimg.title = "title"
demoimg.image.save("logo.png", django_file, save=True)

如果这样配置,这种方法还会触发文件上传到cloudinary/S3

如果模型还没有创建,超级简单:

首先,将图像文件复制到上传路径(在下面的代码片段中假设= 'path/')。

其次,使用如下语句:

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

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

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

这可能不是你想要的答案。但是您可以使用charfield来存储文件的路径,而不是ImageFile。通过这种方式,您可以通过编程方式将上传的图像关联到字段,而无需重新创建文件。