Django图片上传表格无效

时间:2017-07-06 15:00:02

标签: django django-forms django-templates

出于某些原因,在django中,我尝试使用的表单不​​被视为有效。此代码几乎直接来自声称其有效但仍无法正常运行的网站。 我的代码如下。

视图

def display_update_image(request, pk):
if request.method == 'POST':
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        display = Display.objects.get(pk = pk)
        display.image = form.cleaned_data['image']
        display.save()
    return HttpResponseRedirect(reverse('displays'))
else :
    form = ImageForm()
return render(request, 'catalog/update_display_image.html', {'form': form})

TEMPLATE(模板名称为update_display_image.html)

<form method = "post" enctype = "multipart/form-data">{% csrf_token %}
<p>
    <input id = "id" type = "file" class = "" name = "image">
</p>
<input type = "submit" value = "Submit" />

模型

class Display(models.Model):
    title = models.CharField(max_length = 50,)
    image = models.ImageField(upload_to = 'images')
    id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True)

    def __str__(self):
        return self.title

编辑:忘记发布表单代码抱歉

class ImageForm(forms.Form):
    image = forms.ImageField()

进一步编辑:将我的表单类更改为此

class ImageForm(forms.Form):
    class Meta:
        model = Display
        fields = ('image',)

允许表单由于某种原因被读取为有效,但我不明白为什么。不幸的是,这导致我的视​​图方法无法正常工作,因为它无法再读取

display.image = form.cleaned_data['image']

2 个答案:

答案 0 :(得分:2)

如果你的表格是一个模型形式:class ImageForm(forms.ModelForm):你可以将实例传递给表格并保存。

def display_update_image(request, pk):
    if request.method == 'POST':
        display = Display.objects.get(pk = pk)
        form = ImageForm(request.POST, request.FILES, instance=display)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(reverse('displays'))
    else :
        form = ImageForm()
    return render(request, 'catalog/update_display_image.html', {'form': form})

答案 1 :(得分:0)

forms.py中检查您是否有像这样的Django表格:

class ImageForm(forms.ModelForm):
    class Meta:
        model = Display
        fields = ['image',]

template添加{{ form }}而非手动使用input,如下所示:

<form method='post' enctype='multipart-formdata>
{% csrf_token %}
{{ form }}
<input type='submit' value='Update Image'>