Search code examples
djangodjango-formsdjango-file-upload

In Django, how can one access file fields in forms.py?


I have this form class in forms.py in my Django application:

class EmailForm(EmailFormWithoutAttachment):
    attachment = forms.FileField()

I would like to access the file uploaded in forms.py for validation via a clean function to validate its name.

def clean_attachment(self):
    if self.data['attachment'].name == "someFileName.txt":
        raise forms.ValidationError('This file is not allowed.')
    return self.data['attachment']

However, the problem is that an error notes that "attachment" is not found in "QueryDict." I am binding request.FILES to the submission form. I am also using enctype="multipart/form-data" on my forms. I was wondering what is the proper way to access FileField data in forms.py.

Thank you.


Solution

  • Use self.cleaned_data['attachment'] instead of self.data['attachment'].