How to set upload file size limit in Django

This tutorial is based on limiting the uploading file size or restricting a limit to which we can store a large amount of data with less storage data. You might want to have a limit it to a certain amount to store a large data using less space.

Basic Steps

Let’s begin this tutorial by following the below steps:

  1. Start a project.
  2. Start an app.
  3. Create a superuser.

Validators.py file to check the size of file

Now we will create a file named validators.py inside our project which will have a function to check the size of a file.
If the file size is more than 10Mb, it will show an error saying that the maximum size for uploading a file is 10Mb. You can also change it by converting megabytes in bytes.

Create a file named validators.py and code the snippet below:

from django.core.exceptions import ValidationError


def validate_file_size(value):
    filesize= value.size
    
    if filesize > 10485760:
        raise ValidationError("You cannot upload file more than 10Mb")
    else:
        return value

Model to upload a file by validating file size in Django

Create a model to upload and check the validators we have created.

from django.db import models
from validators import validate_file_size


class upload_file(models.Model):
    file_name=models.CharField(max_length=50)
    path=models.FileField(validators=[validate_file_size])
    def __str__(self):
        return self.file_name

This is a very simple model to upload a file where its attributes are file_name and path whose fields are CharField and FileField respectively. Here we have used validator created in validators.py file.

You need to include your app in installed app under settings.py

Also don’t forget to register your model in admin.py

We have created validators.py and our model too.

We just need to migrate our changes we have made yet.

Execute the two statements in terminal:-

python manage.py makemigrations

python manage.py migrate

Run server and check uploading file size limit

At the end, run your server using python manage.py runserver

You will receive a link or you can directly navigate into http://127.0.0.1:8000/admin

Try to upload a file more than 10Mb. You will receive an error showing screen like-

How to set upload file size limit in Django

Thanks for reading this tutorial! Hope you liked this tutorial! Feel free to comment and share you reviews!

KEEP READING! KEEP CODING

Leave a Reply

Your email address will not be published.