表单验证不适用于在Django 1.11中添加图像

时间:2019-01-15 08:07:40

标签: django

我有一个应用程序,我在其中上传多张图像并进行上传。 它工作正常,但如果我单击“上传”,则没有上传任何内容,这会给我一个错误,因为验证工作正常。这是错误:

django.utils.datastructures.MultiValueDictKeyError: "'gallery'"

这是我的代码在这里:

models.py

class GalleryImage(models.Model):

    image = models.ImageField(upload_to='uploads/obituaries', db_index=True)
    obituary = models.ForeignKey(Obituary, related_name="gallery")

    def __str__(self):
        return self.obituary.name

Views.py

class GalleryAddView(View):
    def post(self, request, slug):
        try:
            data = request.FILES['gallery']
            if len(request.FILES.getlist('gallery')) > 10:
                messages.error(request, "Max gallery images limit exceeded! Only 10 images are allowed.")
                return HttpResponseRedirect(
                    reverse('obituary:public', kwargs={'slug': slug}))
            if request.FILES['gallery']:
                for f in self.request.FILES.getlist('gallery'):
                    print(f)
            instance1 = Obituary.objects.get(slug=slug)

            if self.request.FILES:
                for f in self.request.FILES.getlist('gallery'):
                    GalleryImage.objects.create(obituary=instance1, image=f)
            messages.success(request, "Gallery images uploaded successfully!")
            else:
                messages.error(request, 'Please upload some images')

        except Obituary.DoesNotExist:
            messages.error(request, constants.OPERATION_UNSUCCESSFUL)
        return HttpResponseRedirect(reverse('obituary:public', kwargs={'slug': slug}))

forms.py

class GalleryForm(models.ModelForm):

    class Meta:
        model = GalleryImage
        fields = ['image']

template.html

<form class="setting-form" id="create_obit" action="{% url 'obituary:gallery' obituary.slug %}" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <fieldset>
         <div class="col-xs-12">
         {% if gallery|length > 0 %}
                 <h3>Upload More Gallery Photos</h3>
         {% else %}
                 <h3>Upload Gallery Photos</h3>
         {% endif %}
         <div class="dropzone" id="my-awesome-dropzone">
               <div class="fallback">
                    (Maximum image size should be 8 MB)
                       <input type="file" name="gallery" class="form-control input-field" id="id_user_image" accept="image/*" multiple>
              </div>
         </div>
      </div>
         <div class="col-xs-12">
             <div class="form-group">
                  <button type="submit" id="create" class="btn send-btn" >Upload</button>
             </div>
        </div>
</fieldset>
</form>

我不知道我要去哪里。

1 个答案:

答案 0 :(得分:2)

我相信错误在这一行:

data = request.FILES['gallery']

由于您不发送文件,因此request.FILES为空,因此在直接访问时会引发异常。

可能的解决方案是先检查request.FILES是否具有密钥'gallery',否则不要进行检查,请查看以下代码:

 def post(self, request, slug):
        try:
            if request.FILES.get('gallery'):
                data = request.FILES['gallery']
                if len(request.FILES.getlist('gallery')) > 10:
                    messages.error(request, "Max gallery images limit exceeded! Only 10 images are allowed.")
                    return HttpResponseRedirect(
                    reverse('obituary:public', kwargs={'slug': slug}))
                if request.FILES['gallery']:
                    for f in self.request.FILES.getlist('gallery'):
                        print(f)

            instance1 = Obituary.objects.get(slug=slug)
            form = GalleryForm(request.POST, request.FILES)
            if form.is_valid():
                if self.request.FILES:
                    for f in self.request.FILES.getlist('gallery'):
                        GalleryImage.objects.create(obituary=instance1, image=f)
                messages.success(request, "Gallery images uploaded successfully!")
            else:
                messages.error(request, 'Please upload some images')

        except Obituary.DoesNotExist:
            messages.error(request, constants.OPERATION_UNSUCCESSFUL)
        return HttpResponseRedirect(reverse('obituary:public', kwargs={'slug': slug}))