Django - 即使表单无效,如何保存 ImageField

Django - How to Save ImageField Even if Form is Not Valid

我有一个相当标准的模型和形式。我有一些带有 ImageField 的必填字段。当用户选择图像但未填写必填字段时,图像不会保存,用户需要再次 're-upload'。

由于数据库中的行已经存在(因为此表单是 'wizard' 的一部分),我不介意将图片保存在数据库中,即使所有表单都无效必填数据。

这就是我现在所拥有的,当您填写所有必填字段时它会起作用:

def my_view(request):
    instance = MyModel.objects.get(user=request.user)
    form = MyForm(instance=instance)

    if request.POST:
        form = MyForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            new_instance = form.save(commit=False)

            if request.FILES and request.FILES['photo']:
                uploaded_photo = request.FILES['photo']
                new_instance.photo = uploaded_photo

            new_instance.save()
            return HttpResponseRedirect(reverse('new_url'))

    return render_to_response('current_template.html', locals(), context_instance=RequestContext(request))

这是我尝试将图片保存在数据库中的方法,即使其他字段未填写,但我收到错误 Django 上传错误 - 上传有效图片(不是图片或已损坏):

def my_view(request):
    instance = MyModel.objects.get(user=request.user)
    form = MyForm(instance=instance)

    if request.POST:
        form = MyForm(request.POST, request.FILES, instance=instance)

        if request.FILES and request.FILES['photo']:
            uploaded_photo = request.FILES['photo']
            instance.photo = uploaded_photo
            instance.save()

        if form.is_valid():
            new_instance = form.save()
            return HttpResponseRedirect(reverse('new_url'))

    return render_to_response('current_template.html', locals(), context_instance=RequestContext(request))

这是我的表格(相当简单):

class MyForm(ModelForm):
    first_name = forms.CharField(label='First Name', max_length=50, required=True)
    last_name = forms.CharField(label='Last Name', max_length=50, required=True)
    photo = forms.ImageField(required=False)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

    class Meta:
        model = MyModel
        fields = ('first_name','last_name', 'photo')

这是我的模型(同样非常简单):

class MyModel(models.Model):
    first_name = models.TextField(max_length=50)
    last_name = models.TextField(max_length=50)
    photo = ImageField(upload_to=get_photo_path,null=True,blank=True)

这就是我让它工作的方式。请注意,当表单无效时,'else' 中的表单构造函数没有 'request.FILES' 作为参数。这就是 Django 显示错误消息的原因。

if form.is_valid():
    instance = form.save(commit=False)

    if request.FILES and request.FILES['photo']:
        instance = save_photo(instance, request.FILES['photo'])

    instance.save()
    return HttpResponseRedirect(reverse('url'))
else:
    if request.FILES and request.FILES['photo']:
        instance = save_photo(instance, request.FILES['photo'])
        form = InstanceForm(request.POST, instance=instance)