Python 德扬戈。如何保存使用Pillow编辑的内容文件

Python 德扬戈。如何保存使用Pillow编辑的内容文件,python,django,pillow,Python,Django,Pillow,我正试图保存一张我用请求下载的图像,然后用枕头编辑到模型中的图像字段。但是创建对象时没有图像 这就是我所拥有的: 设置.py MEDIA_ROOT = BASE_DIR + "/media/" MEDIA_URL = MEDIA_ROOT + "/magicpy_imgs/" models.py def create_path(instance, filename): path = "/".join([instance.group, instance.name]) return

我正试图保存一张我用
请求下载的图像
,然后用
枕头
编辑到模型中的
图像字段
。但是创建对象时没有图像

这就是我所拥有的:

设置.py

MEDIA_ROOT = BASE_DIR + "/media/"
MEDIA_URL = MEDIA_ROOT + "/magicpy_imgs/"
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 ...')

它创建了对象,但没有图像。请帮忙。我已经尝试解决这个问题好几个小时了。

试试这个
self.image.save(一些文件路径,内容文件(图像字符串))
。在我看来,您不需要在model中重写
save()

Background 虽然主要用于,但也可以用于其他目的。应该注意的是,MemoryFileUploadHandler用于处理用户使用Web表单或小部件将文件上载到服务器时的情况。然而,您所处理的情况是,用户只提供一个链接,而您将文件下载到web服务器上

让我们回忆一下,它本质上是对存储在文件系统中的文件的引用。数据库中只输入文件名,文件内容本身存储在存储系统中。Django允许您指定不同的存储系统,以便在需要时将文件保存在云上

解决方案 您所需要做的就是将使用
Pillow
生成的图像内容以及文件名传递到
ImageField
。这些内容可以通过内存中的
文件
内容文件
发送。但是,没有必要同时使用这两种方法

这就是你的模型

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')
脚注 添加了异常处理,因为事情可能会出错


不要使用JPEG和图像/JPEG,你应该使用answers.headers['Content-type']并选择合适的一个。

谢谢你的回答,这让我意识到,在
URLField
+1中调用
save
是不可能的。。。尝试将其更改为
ImageField
,但没有意义(也不起作用),因为用户提交了一个url,我将使用该url从其他网站请求图像。所以在这种情况下,我决定使用
ModelForm
和CBV,并将所有内容都更改为基于函数的视图。它仍然无法保存图像,但至少这段代码对我来说更有意义。有什么想法吗?在模型中尝试使用和不使用自定义保存方法。