I'm still new to Django and have found some excellent answers on how to restrict the type of file uploaded through Django's FileField. However, these answers deal with the case of a single file upload. I am dealing with the case of a multiple file upload, like so:
forms.py
from django.core.exceptions import ValidationError
class DocumentForm(forms.Form):
def clean_docfile(self):
file = self.cleaned_data["docfile"]
if not file.name.endswith('.txt'):
raise ValidationError(u'Error: Text files only.')
return file
docfile = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}),
label='Select some files'
)
models.py
from django.db import models
from myproject.myapp.validators import validate_file_extension
class Document(models.Model):
docfile = models.FileField(upload_to=_upload_path, validators = [validate_file_extension])
validators.py
from django.core.exceptions import ValidationError
def validate_file_extension(value):
if not value.name.endswith('.txt'):
raise ValidationError(u'Error: Text files only.')
I want the user to be able to upload multiple files at one time, but have all files rejected if at least one file is the incorrect file type.
Currently, clean_docfile only seems to check the name of the file that appears last alphabetically. So, the file selection [A.txt, B.txt, C.png] does not upload (as intended), but [A.txt, B.png, C.txt] does upload (when it shouldn't). When I look at the value of the object self.cleaned_data["docfile"] within my clean_docfile function, it appears to only store the attributes of the file that appears last alphabetically. How do I recover all of the uploaded file names?