这简直要了我的命!
我正在使用django-filebrowser,我想创建一个画廊应用程序,利用它的上传功能来管理图像。
我有一个gallery模型,它允许用户在服务器上选择或创建一个目录,并将文件上传到该文件夹以显示在图库中。我希望自动搜索用户已将图像上传到并选择的目录,然后自动为文件夹中的每个图像创建Image实例。
class Gallery(model.Models):
gallerydirectory = FileBrowserField(...)
title = ...
description ...
class Image(model.Models):
image_field = models.ImageField()
问题是FileBrowser表示图像的方式与Django不同,但我想使用DJango ImageFields,因为我可以在模板端使用其他应用程序(sorl缩略图)。
我有文件所需的所有数据,例如文件名、路径等,我只是无法让Django创建ImageField的实例,而不是真正地重新上传图像。我只是想填充它。
我看到了另一个线程here,它提出了以下建议:
for image in filebrowser_image_objects_list:
f = File(open('path-to-file-on-server','r'))
i = Image()
i.image_field('filename.png',f.read())
但这给了我一个启示:
SuspiciousOperation error
Attempted access to '/filename.png' denied
这表明该路径未被正确读取。我已经打印了文件对象的属性,它打开了正确的图像,只是没有传递给ImageField
如果能帮上忙,我们将不胜感激!
更新
我已经放弃了尝试完成这项工作,因为它太混乱了。我上面遇到的问题是,我将ImageField的upload_field设置为'/‘,但是没有注意到,这意味着文件被写到了’/omething.png‘。
我已经对其进行了修改,以便图像现在也使用FileBrowserField,而不是ImageField。
发布于 2011-11-01 18:11:18
我将此标记为已回答,因为这是正确的方法:
from django.core.files import File
image_model.image_field('path', File().read())
发布于 2017-09-11 23:27:34
我可能遗漏了一些东西,但这对我很有效:
from a1.models import Model1
from django.core.files.images import ImageFile
m = Model1.objects.create()
m.f1 = ImageFile(open("1.png", "rb"))
m.save()
对于以下型号:
class Model1(models.Model):
f1 = models.ImageField()
这种方式不起作用:
m.f1('1.png', File.read(open('1.png', 'r')))
上面写着:
TypeError: 'ImageFieldFile' object is not callable
检查了Django 1.7,1.11。
发布于 2019-08-31 03:54:46
这对我在Python3上的Django 2很有效
from urllib.request import urlopen
from urllib.parse import urlparse
from io import BytesIO
from django.core.files.images import ImageFile
from .models import ModelWithImageField
# Solving for SSL Error
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
url = https://www.someurl.com/image.png?other_params_if_they_exist
image_file_name = urlparse(url).path.split('/')[-1]
image_file_content = BytesIO(urlopen(url).read())
ModelWithImageField().image_field.save(image_file_name, image_file_content)
https://stackoverflow.com/questions/4258605
复制相似问题