I am trying to figure out how to process multiple files from a filefield in Django. I have figured out how to add the "multiple" attribute to the form field. What I need to do now is loop through each file and perform some logic.
I have a form with fields like this (in views.py):
class RecipientListForm(forms.Form):
name = forms.CharField()
recipients = forms.CharField(
required=False,
widget=forms.Textarea(attrs={'placeholder':"James Jameson, james.jameson@aol.com"}),
label="Paste recipient information (comma-separated, in 'name, email' format)")
recipients_file = RecipientsFileField(
required=False,
widget=forms.FileInput(attrs={'multiple':"true"}),
label="Or upload a .csv file in 'name, email' format (max size %dMB)" % RecipientsFileField.MAX_FILESIZE_MB)
def __init__(self, account, recipient_list=None, *args, **kwargs):
super(RecipientListForm, self).__init__(*args, **kwargs)
self.account = account
self.recipient_list = recipient_list
def clean(self, *args, **kwargs):
...
RecipientsFileField looks like this (also in views.py):
class RecipientsFileField(forms.FileField):
MAX_FILESIZE_MB = 30
def validate(self, value):
super(RecipientsFileField, self).validate(value)
if not value: return
fname = value.name
if (value.content_type not in (('text/csv',) + EXCEL_MIMETYPES) or not re.search(r'\.(xlsx?|csv)$', fname, re.I)):
raise forms.ValidationError('Please upload a .csv or .xlsx file')
if value.size >= self.MAX_FILESIZE_MB * 1024 * 1024:
raise forms.ValidationError('File must be less than %dMB' % (self.MAX_FILESIZE_MB,))
I have tried to perform my logic in the clean
method of RecipientListForm
but I have only been able to access the first file that is uploaded, it seems that the other files are not uploaded. I have looked at the docs but the way these forms are setup don't seem to be reflected in the documentation about forms, unless I am just looking in the wrong place. Thanks in advance!