Validate File Size and Type

A snippet showing how to validate uploaded file size and type.


# forms.py

from django import forms

ALLOWED_TYPES = {"application/pdf", "text/plain"}
MAX_MB = 5

class DocumentForm(forms.Form):
    file = forms.FileField()

    def clean_file(self):
        f = self.cleaned_data["file"]
        if f.size > MAX_MB * 1024 * 1024:
            raise forms.ValidationError(f"File too large (>{MAX_MB} MB).")
        ctype = getattr(f, "content_type", None)
        if ctype not in ALLOWED_TYPES:
            raise forms.ValidationError("Only PDF or TXT files are allowed.")
        return f
      
Explanation:
  • Always validate both size and content-type; consider scanning contents if needed.
  • Category Forms & Validation
  • Total Views 1294
  • Last Modified 03 January, 2026
  • Tags #forms #file upload #validation #media
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.