如何在Django中上传具有一个值的多个图像

时间:2019-11-22 11:28:48

标签: django django-forms django-templates

我正在Django应用程序中尝试用一个字段上传多个图像。

该怎么做?

涉及以下文件:

upload.html

<form action="#" method="post" enctype="multipart/form-data">
    {% csrf_token %}

    <input type="text" name="image_id" placeholder="Image Id">
    <input type="file" name="file" multiple>
    <button type="submit"> Upload </button>
</form>

在这里,单个字段image_id用于保存5个图像。

views.py

def multi_image(request):
    if request.method == 'POST':
        img_id = request.POST.get('image_id')
        file = request.FILES.getlist('file')
        data_save = Res(image_id = img_id )
        data_save.save()
        filter_data = Res.objects.filter(image_id= img_id)
        if len(filter_data) > 0:
            for i in file:
                print(i)
                Res.objects.create(image= i)

    return render(request, 'upload.html', {}) 

models.py

class Res(models.Model):
    image_id= models.CharField(max_length=10, blank=True, null=True)
    image = models.FileField(upload_to='images', blank=True, null=True)

forms.py

class FileForm(forms.Form):
    class Meta:
        model = Res
        fields = '__all__'

0 个答案:

没有答案