如何使用modelformset上传多个图像 - Django

时间:2015-10-01 13:43:54

标签: django django-forms modelform

我正在尝试创建一个系统,允许用户能够添加新的Vegetable对象,上传缩略图和多个图像和文件 - 所有这些都来自AddVegetable页面,并且能够像蔬菜类型一样轻松输出被过滤以显示在不同的页面上

我试图通过下面的代码来实现这一目标,但它不会起作用,我无法弄清楚为什么确切地说,因为我正在获得一个KeyError' image' ;但是我不知道为什么。我正在以正确的方式解决这个问题吗?

我暂时无视图像处理,

models.py

class Vegetable(models.Model):
    title = models.CharField(max_length=0)
    category = models.CharField(max_length=50,
                                choices=CATEGORY_CHOICES)
    description = models.CharField(max_length=1000, null=True)
    thumbnail = models.ImageField(upload_to = 'uploaded_images/')
    attachments = models.FileField(upload_to = uploaded_files/)
    date_added = models.DateTimeField('Date Added', default=datetime.datetime.now)

class VegetableImage(models.Model):
    vegetable = models.ForeignKey(Vegetable, default=None)
    image = models.ImageField(upload_to='images/vegetable',
                             verbose_name='image',)

forms.py

Class AddVegetable(ModelForm):
    class Meta:
          model = Vegetable
          fields = ['title', 'category', 'description', 'thumbnail',
                    'images', 'attachments', 'date_added',]

class ImageForm(ModelForm):
    image = ImageField(label='image')
    class Meta:
        model = VegetableImage
        fields = ['image',]

views.py

def AddVegetable(request):

ImageFormSet = modelformset_factory(VegetableImage,
                                    form=ImageForm, extra=4)

if request.method == 'POST':

    VegetableForm = AddVegetableForm(request.POST)
    formset = ImageFormSet(request.POST, request.FILES,
                           queryset=VegetableImage.objects.none())

    if VegetableForm.is_valid() and formset.is_valid():

        VegetableForm.save()

        for form in formset.cleaned_data:
            image = form['image']
            picture = VegetableImage(vegetable=VegetableForm, image=image)
            picture.save()

        return HttpResponseRedirect('/vegetable/')
    else:
        print (VegetableForm.errors, formset.errors)

else:
    VegetableForm = AddVegetableForm()
    formset = ImageFormSet(queryset=VegetableImage.objects.none())

return render(request, 'vegetable/add.html',
              {'VegetableForm': VegetableForm, 'formset': formset},
              context_instance=RequestContext(request))

template.html

<form action="/vegetable/add/" method="POST" enctypr="multipart/form-data"> 
{% csrf_token %}
    <table>

            <p> {{ VegetableForm.as_ul }}</p>

            {{ formset.management_form }}
            {% for form in formset %}
            {{ form }}
            {% endfor %}

    </table>

    <input type="submit" value="Post">
</form>

1 个答案:

答案 0 :(得分:1)

当您致电VegetableForm.save()时,它会返回实例,因此您应该

vegetable = AddVegetableForm.save()

saving objects in a formset上的文档建议调用formset.save(),它返回实例列表。您可以使用save()拨打commit=False,设置蔬菜,然后保存到数据库。

images = formset.save(commit=False)
for image in images:
    image.vegetable = vegetable
    image.save()