Django upload file size limit and restriction

Question:

I have a form in my app where users can upload files so how can i set a limit to the uploaded file size and type ?

**models.py**
class Document(models.Model):
    emp = models.ForeignKey(Emp, null=True, on_delete=models.SET_NULL)
    Description = models.CharField(max_length=100, null=True)
    Fichier = models.FileField(upload_to='file/')
    data_created = models.DateTimeField(auto_now_add=True, null=True)

**forms.py**
class documentForm(ModelForm):
    class Meta:
        model = Document
        fields = '__all__'
        exclude = []

**view.py**
def createDocument(request):
    forms = documentForm()

    if request.method == 'POST':
        forms = documentForm(request.POST, request.FILES)
        if forms.is_valid():
            forms.save()
            return redirect('/')

    context = {'forms':forms}
    return render(request, 'accounts/document_form.html', context)
Asked By: Robin Langlois

||

Answers:

from django import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _

# 2.5MB = 2.5 * 1024 * 1024 = 2621440
# 5MB = 5 * 1024 * 1024 = 5242880
# 10MB = 10 * 1024 * 1024 = 10485760
# n MB = n * 1024 * 1024 = ...

# I write this example for 5 MB size limit for you
MAX_UPLOAD_SIZE = "5242880"

class documentForm(forms.ModelForm):
    def clean(self):
        self.check_file()
        return self.cleaned_data

    def check_file(self):
        content = self.cleaned_data["Fichier"]
        content_type = content.content_type.split('/')[0]
        if content._size > int(MAX_UPLOAD_SIZE):
            raise forms.ValidationError(_(f"Please keep file size under {(filesizeformat(MAX_UPLOAD_SIZE)}. Current file size {filesizeformat(content._size)}"))
        return content
        
    class Meta:
        model = Document
        fields = '__all__'

Also, you have more ways to do this restriction in different levels of your code, for more information see References.

References:

Validate by file content type and size [djangosnippets]

Django File upload size limit [stackoverflow]

File Uploads [django-docs]

Uploaded Files and Upload Handlers [django-docs]

Answered By: Javad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.