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

时间:2015-12-07 16:31:16

标签: python django django-forms django-views

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

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作为后端。我不确定这与它有什么关系。

如何将临时图像保存到配置文件图像?

2 个答案:

答案 0 :(得分:1)

我认为您可能希望先将表单保存到模型中,然后再更新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()

答案 1 :(得分:0)

您的代码对我来说有点混乱。据我了解,您是从profile_image2拍摄并将其分配到profile_image字段的?如果这是你正在尝试的那么这将是一个可能的答案:

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

[初学者这里可能会有轻微的错误,但如果我正在做你正在做的事情,我将如何解决这个问题]