Limiting Upload File Size with Django Forms

A common use case in any web application is to allow users to upload files such as images, videos, PDFs, etc. But left unrestricted, this could lead to all sorts of problems including users uploading files that are too large for the system or application to handle.

File size restrictions can be placed on the upload in multiple ways including with JavaScript, web server configuration changes and within your application code. I definitely recommend using all of the above, but for this post, we’ll look at how to handle this in Django by subclassing Django’s FileField and ImageField form fields and adding some extra logic to the clean method.

First, define a max upload size within your settings (in bytes).

Next, define the new fields (I usually stick these in app/forms/

You can now make use of these new fields from within your form class. Note that content_types is required for RestrictedFileField while max_upload_size is optional for both fields (defaults to whatever you specified for MAX_UPLOAD_SIZE in your settings).

And remember that the content-type is still user supplied (i.e. it’s a header coming from whatever submitted the form), so be sure to verify that the uploaded file contains the content-type you’re expecting.

2 thoughts on “Limiting Upload File Size with Django Forms”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s