Django Admin 保存模型 - 给表单字段赋新值

3 投票
2 回答
3801 浏览
提问于 2025-04-30 16:36
def save_model(self, request, obj, form, change):
    basewidth = 650
    img = PIL.Image.open(form.cleaned_data['image_file'])

    if img.size[0] > basewidth:
        wpercent = (basewidth / float(img.size[0]))
        hsize = int((float(img.size[1]) * float(wpercent)))
        img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)

        form.cleaned_data['image_file'] = img

        form.save()
    else:
        form.save()

这段代码还是在保存原始图片,而不是缩放后的图片。

form.cleaned_data['image_file'] = img

这一行看起来不对。我怎么才能把新的缩放图片赋值给表单字段呢?

暂无标签

2 个回答

1

@Ngenator说得对。你遇到的问题是因为你需要把form.save()改成obj.save()。

下面是我相信能解决问题的代码:

def save_model(self, request, obj, form, change):
    basewidth = 650
    img = PIL.Image.open(obj.image_file)

    if img.size[0] > basewidth:
        wpercent = (basewidth / float(img.size[0]))
        hsize = int((float(img.size[1]) * float(wpercent)))
        img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
        obj.image_file = img

    obj.save()
1

如果你看看文档,https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model,你会发现obj是模型的一个实例。你需要修改的是obj.your_image_field,而不是表单中的字段。

撰写回答