Django使用表单内的表单验证图像或文件

时间:2020-07-12 10:07:33

标签: django django-forms

您好,我在这里遇到多个具有相同字段的图像的麻烦。 据我在django教程中知道的,他们告诉了这个。

  for f in request.FILES.getlist('files'):
     # do something (validate here maybe)

我不太了解。像我一样手动验证吗?如果可以,为什么? 无论如何,他们提供了另一种方法

  files = forms.FileField(widget=ClearableFileInput(attrs={'multiple': True})

这不是我想要的方式。它是self.cleaned_data ['files']仅给出一个输出(这里有类似的问题),而django / multiupload在我的经验上有一个错误,可惜修复它太慢了:(。

我想要的是验证每个文件并通过ImageField给每个错误,因为我喜欢它在验证文件而不是自己编写代码。

因此,我编写了一个原型代码。

forms.py

class ImageForm(forms.Form):
   # validate each image here
   image = forms.ImageField()

class BaseForm(forms.Form):
   # first form
   ping = forms.CharField()

   #images = SomeThingMultipleFileField that will raise multiple errors each validate image.
   # since no option I decided to do that. below.
   # so for decoration that images is required.
   images = forms.ImageField()

   def handle(self, request, *args, **kwargs):
      #custom function 
      image_list = []
      errors = []
      
      # validate each image in images via another form
      # if there is errors e.g this field is required will be append to errors = []
      for image in request.FILES.getlist('images'):
          data = ImageForm(image)
          
          if data.is_valid():
             image_list.append(data.cleaned_data['image'])
             
          else:
             errors.append(data.errors)
     if errors:
          # raise errors
     # return the data    

views.py

def base(request):
   # this is an api
   # expected input should be from the code or format
   # {'ping': 'test', 'images': 1.jpg, 'images': 2.jpg}
   # This is not the actual view code.

   data = forms.BaseForm(request.POST, request.FILES)
   if data.is_valid():
      value = data.handle(request)
      return JSONResponse({'data': value})
   return JSONResponse({'errors': data.errors})

说实话,这并不优雅,但现在遇到了麻烦,没有其他选择,我可以考虑一下。 我的代码中的问题是

data = ImageForm(image) 

不读取文件,因此image_list始终为空

  1. 那么有人可以在这里帮助我吗?我被困住了
  2. 还有更好的方法吗?
  3. 我还想知道是否会出现一般错误,例如一个图像是否无效,它会像{'files':'其中一个图像无效。'}
  4. 一样触发

1 个答案:

答案 0 :(得分:0)

到目前为止,我再次测试过 似乎它需要数据格式,普通格式的文件。 为此。

forms.py

... # previous code
# data = ImageForm(image) , old code
data = ImageForm({}, {'image': image})

这样,它将填充默认的QueryDict:{},参数中的MultiValueDict

可以回答数字3。 代替

# previous code
else:
  errors.append(error)

现在应该是

   raise ValidationError(_('Your error'))

有更好的方法吗? 我可悲的是,我想的不多。所以有人在这里绊倒。随时发表评论。非常感谢您的帮助。