Accept Only Specific File Types in Django File Upload

Accept Only Specific File Types in Django

There are times that we only have to accept specific file types and limit file size in our file uploads. This time, I am going to show simple steps to make a FileField accept only specific file types.

Assuming that we already have a working model, views and template(s) are already working.

Step 1:

Create a file and name it formatChecker.py. This is the code for your formatChecker.py:

We are now done with step 1. Basically, what formatChecker.py does is it overrides the FileField class. What that snippet does is it checks the file type of the file and checks the file size during the process of form validation. It returns error messages if a user uploaded an invalid file.

Step 2:

Change your field “FileField” to “ContentTypeRestrictedFileField”.

To make things more clear, I’ll show you an example.

Example:

For the first value of the parameter of  ContentTypeRestrictedFileField, “upload_to”, this is where the file goes when uploaded. The second value, “content_types”, is a list of accepted file types. The third value is the  allowed maximum size of the file.

That’s it. We can now restrict file types that we do not want to be uploaded.