将表单图像字段保存​​到 Django 中视图中的另一个图像字段

save form imagefield to another image field in view in django

我有以下视图,它在保存之前将一个图像字段保存​​到另一个图像字段:

if request.method == 'POST':
        form = PlayerForm(request.POST, request.FILES, instance=current_player)
        if form.is_valid():

            temp_image = form.cleaned_data['profile_image2']
            form.cleaned_data['profile_image'] = temp_image
            form.profile_image = temp_image


            form.save() 

            return redirect('player')

问题是图像没有保存。我正在使用 boto 作为后端。我不确定这是否与它有关。

如何获取临时图像以保存到个人资料图像?

我认为您可能希望先将表单保存到模型中,然后再更新 profile_image

from django.core.files.base import ContentFile

if form.is_valid():
    new_player = form.save()

    temp_image = new_player.profile_image2
    # duplicate the image for "profile_image2"
    dup_file = ContentFile(temp_image.read())
    dup_file.name = temp_image.name
    new_player.profile_image = dup_file
    new_player.save()

你的代码让我有点困惑。据我了解,您是从 profile_image2 获取图像并将其分配给 profile_image 字段吗?如果那是您正在尝试的,那么这将是一个可能的答案:

image = form['profile_image2']
photo = PlayerForm(profile_image=image)
photo.save()

[这里是初学者,所以可能会出现一些小错误,但这就是我如何着手解决这个问题,如果我正在做你正在做的事情]