0

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)
1

1 Answer 1

1
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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.