How to limit file types on file uploads for ModelForms with FileFields?

dangerChihuahua007 picture dangerChihuahua007 · Jun 23, 2011 · Viewed 25.7k times · Source

My goal is to limit a FileField on a Django ModelForm to PDFs and Word Documents. The answers I have googled all deal with creating a separate file handler, but I am not sure how to do so in the context of a ModelForm. Is there a setting in settings.py I may use to limit upload file types?

Answer

user1144136 picture user1144136 · Jan 11, 2012

Create a validation method like:

def validate_file_extension(value):
    if not value.name.endswith('.pdf'):
        raise ValidationError(u'Error message')

and include it on the FileField validators like this:

actual_file = models.FileField(upload_to='uploaded_files', validators=[validate_file_extension])

Also, instead of manually setting which extensions your model allows, you should create a list on your setting.py and iterate over it.

Edit

To filter for multiple files:

def validate_file_extension(value):
  import os
  ext = os.path.splitext(value.name)[1]
  valid_extensions = ['.pdf','.doc','.docx']
  if not ext in valid_extensions:
    raise ValidationError(u'File not supported!')