Django的。如何保存用枕头编辑的ContentFile [英] Django. How to save a ContentFile edited with Pillow
问题描述
我正在尝试使用请求
下载图片,然后使用枕头
编辑到 ImageField
在模型中。但是这个对象是在没有图像的情况下创建的。
I'm trying to save an image I download with requests
and then edit with Pillow
to ImageField
in a model. But the object is being created without the image.
这是我所拥有的:
settings.py
settings.py
MEDIA_ROOT = BASE_DIR + "/media/"
MEDIA_URL = MEDIA_ROOT + "/magicpy_imgs/"
models.py
models.py
def create_path(instance, filename):
path = "/".join([instance.group, instance.name])
return path
class CMagicPy(models.Model):
image = models.ImageField(upload_to=create_path)
....
# Custom save method
def save(self, *args, **kwargs):
if self.image:
image_in_memory = InMemoryUploadedFile(self.image, "%s" % (self.image.name), "image/jpeg", self.image.len, None)
self.image = image_in_memory
return super(CMagicPy, self).save(*args, **kwargs)
forms.py
class FormNewCard(forms.Form):
imagen = forms.URLField(widget=forms.URLInput(attrs={'class': 'form-control'}))
views.py
def new_card(request):
template = "hisoka/nueva_carta.html"
if request.method == "POST":
form = FormNewCard(request.POST)
if form.is_valid():
url_image = form.cleaned_data['imagen']
group = form.cleaned_data['grupo']
name = form.cleaned_data['nombre']
description = form.cleaned_data['descripcion']
answer = requests.get(url_image)
image = Image.open(StringIO(answer.content))
new_image = image.crop((22, 44, 221, 165))
stringio_obj = StringIO()
try:
new_image.save(stringio_obj, format="JPEG")
image_stringio = stringio_obj.getvalue()
image_file = ContentFile(image_stringio)
new_card = CMagicPy(group=group, description=description, name=name, image=image_file)
new_card.save()
finally:
stringio_obj.close()
return HttpResponse('lets see ...')
它创建对象但没有图像。请帮忙。
It creates the object but with no image. Please help. I've been trying to solve this for hours.
推荐答案
背景
尽管 InMemoryUploadedFile 主要是为了由 MemoryFileUploadHandler 使用,它也可以用于其他目的。应该注意的是,MemoryFileUploadHandler用于处理用户使用webform或widget创建一个文件到您的服务器上的 的情况。但是,您正在处理的情况是用户仅提供链接的情况,并且您将文件下载到您的Web服务器。
Background
Though InMemoryUploadedFile is primarily intended to be used by MemoryFileUploadHandler, it can be used for other purposes as well. It should be noted that MemoryFileUploadHandler is for handling the situation when a user uploads a file to your server using a webform or a widget. However what you are handling is a situation the user merely provides a link and you download a file on to your web server.
让我们也回想起 ImageFile 本质上是对存储在文件系统上的文件。只有文件的名称输入到数据库中,文件的内容本身就存储在存储系统中。 Django允许您指定不同的存储系统,以便在需要时可将文件保存在云端。
Let us also recall that ImageFile is essentially a reference to a file stored on your filesystem. Only the name of the file is entered in the database and the file's content itself is stored in the storage system. Django allows you to specify different storage systems so that the file can be saved on the cloud if you need to.
所有您需要做的是传递您使用枕头
,文件名为 ImageField
。该内容可以通过 InMemoryUploaded
文件或一个 ContentFile
发送。但是没有必要同时使用。
All you need to do is to pass the content of the image that you generate using Pillow
with a filename to ImageField
. And that content can be sent through a InMemoryUploaded
file or a ContentFile
. However there isn't a need to use both.
所以这是你的模型。
class CMagicPy(models.Model):
image = models.ImageField(upload_to=create_path)
# over ride of save method not needed here.
这是您的观点。
try:
# form stuff here
answer = requests.get(url_image)
image = Image.open(StringIO(answer.content))
new_image = image.rotate(90) #image.crop((0, 0, 22, 22))
stringio_obj = StringIO()
new_image.save(stringio_obj, format="JPEG")
image_file = InMemoryUploadedFile(stringio_obj,
None, 'somefile.jpg', 'image/jpeg',
stringio_obj.len, None)
new_card = CMagicPy()
new_card.image.save('bada.jpg',image_file)
new_card.save()
except:
# note that in your original code you were not catching
# an exception. This is probably what made it harder for
# you to figure out what the root cause of the problem was
import traceback
traceback.print_exc()
return HttpResponse('error')
else:
return HttpResponse('done')
脚注< h2>
异常处理已添加,因为事情可以而且会出错。
Footnotes
Exception handling has been added because things can and will go wrong.
而不是使用JPEG和image / jpeg应该使用answers.headers ['Content-type']并选择适当的。
Instead of using JPEG and image/jpeg you should use answers.headers['Content-type'] and choose the appropriate one.
这篇关于Django的。如何保存用枕头编辑的ContentFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!