Error when validating file extension for multiple file upload

When uploading multiple files using the code in this page https://docs.djangoproject.com/en/4.2/topics/http/file-uploads/#uploading-multiple-files, everything works.

but, when i add the FileExtensionValidator to the model field it raises an error:

'list' object has no attribute 'name'

from this file: python3.11/site-packages/django/core/validators.py line: #561

models.py

class Media(models.Model):
    title = models.CharField(blank=True, null=True)
    file = models.FileField(
        upload_to="library/",
        validators=[FileExtensionValidator(["png", "gif", "jpeg", "jpg", "webp"])],
    )

views.py

class MyView(View):
     ...
     def post(self, request, *args, **kwargs):
          form = UploadForm(request.POST, request.FILES, request=request)
          if form.is_valid():
              form.save(request=request)
              return redirect(reverse("media:upload"))
          return render(
              request,
              "media/upload.html",
              {"form": form},
          )

forms.py

class UploadForm(forms.ModelForm):
    file = MultipleFileField(required=False)

    class Meta:
        model = Media
        fields = ["title", "file"]

Hey, take a look at these File Uploads | Django documentation | Django

yes I did, the problem raised after i added the file extension validator to that code.

I’m not sure this would work without the validator. How do you expect a list of files (as returned by a MultipleFileField) will be saved in a single FileField ?

No, the code crashes on this line: if form.is_valid(): when I added the FileExtensionValidator. and does not pass that line.

I will save each image alone later.

You are using a ModelForm but the form fields definition in not in sync with the model fields definition. On the form, file correspond to multiple files (i.e. is a list of files) but on the model file is a single file, so on form field validation, passing a list of files to a validator which is supposed to validate a single file leads to the error (the validator search for the name of file to validate on the list because it expect it to be a single File, not a list).

I don’t know how you will save each file independently and how you will make a single Media object linked to several files but:

  • either you should not use a ModelForm
  • or use another field name (e.g. files) on the form for handling the multiple files and manage those multiple files in the save method of the form

To add to this, you do not make a single instance of Media that refers to multiple files. You need to create multiple Media instances, each instance being a reference to a single file.