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

时间:2015-10-27 16:42:16

标签: django django-models django-1.4 imagefield

我有一个相当标准的模型和形式。我有一些ImageField的必填字段。当用户选择图像但未填写必填字段时,图像不会保存,用户需要再次“重新上传”。

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

这就是我现在所拥有的,当你填写所有必填字段时,它就有用了:

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))

这是我试图在DB中保存图片的内容,即使其他字段未填充,但我收到错误 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)

1 个答案:

答案 0 :(得分:0)

这就是我的工作方式。请注意,当表单无效时,'request'没有'request.FILES'作为'else'中表单构造函数的参数。这就是让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)