【问题标题】:Django Admin image upload not saving on databaseDjango Admin图像上传未保存在数据库中
【发布时间】:2013-10-22 16:06:06
【问题描述】:

我需要在保存到数据库之前调整图像大小,所以我重写了 save 方法:

from PIL import Image

class Categorias(models.Model):
image_height = models.PositiveIntegerField(editable=False,null=True)
image_width = models.PositiveIntegerField(editable=False,null=True)
the_image = models.ImageField(upload_to="uploads/image/category",width_field="image_width",height_field="image_height")

def save(self):
    if not self.id and not self.the_image:
        return;

    image = Image.open(self.the_image)
    ratio_height = (890*self.image_height)/self.image_width     
    size = (890,ratio_height)
    image = image.resize(size, Image.ANTIALIAS)
    image.save(self.the_image.path)

图像已调整大小并写入我的媒体文件夹,但问题是注册表未保存在数据库中。

我不知道我错过了什么。


toad013 帮助了我,我可以将注册表保存到数据库中,但随后我将两张图像写入我的媒体文件夹,一张是原始图像,另一张使用此代码调整大小:

def save(self):
    if not self.id and not self.the_image:
        return;

    image = Image.open(self.the_image)
    ratio_height = (890*self.image_height)/self.image_width     
    size = (890,ratio_height)
    image = image.resize(size, Image.ANTIALIAS)
    image.save(self.the_image.path)     
    super(Categorias, self).save()

【问题讨论】:

    标签: python database django model


    【解决方案1】:

    你应该仍然需要调用原始的保存函数来保存对象

    super(Categorias, self).save()
    

    【讨论】:

    • 现在注册表正在保存到数据库中,但现在我保存了原始图像,其中包含原始宽度和高度以及调整大小的版本。是否可能只有调整大小的版本?
    • hmmm 删除 image.save(...) 并确保“super”行位于末尾并且在 super 之前只需分配您制作的新调整大小的图像:“self.image = image .resize(大小,Image.ANTIALIAS)”。这样你就可以让 django 完成所有字段的保存和更新
    • Getting: TypeError at /admin/imagens/categorias/add/ 'tuple' object is not callable 异常值: 'tuple' object is not callable def save(self): if not self.id and不是self.the_image:返回; image = Image.open(self.the_image) ratio_height = (890*self.image_height)/self.image_width size = (890,ratio_height) image = image.resize(size, Image.ANTIALIAS) #image.save(self.the_image .path) self.image = image.size(size, Image.ANTIALIAS) super(Categorias, self).save()
    • image.resize not image.size ...和self.the_image(对不起,我的错字)基本上你将调整大小的图像从“image.resize”分配给self.the_image,然后只有django保存对象
    • 获取:异常类型:AttributeError 异常值:宽度
    猜你喜欢
    • 1970-01-01
    • 2021-06-08
    • 2021-03-08
    • 2016-11-22
    • 2014-08-09
    • 1970-01-01
    • 2018-09-05
    • 2015-04-15
    相关资源
    最近更新 更多