Skip to content

Add MaxFileSizeValidator and MinFileSizeValidator for file size constraints #9738

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

mahdirahimi1999
Copy link
Contributor

@mahdirahimi1999 mahdirahimi1999 commented Jul 12, 2025

Add file size validators for FileField and ImageField

Adds two new validators to enforce file size constraints on uploaded files:

Background

In many of our DRF and Django projects, we work extensively with FileField and ImageField and need to validate file sizes. I've been creating these validators locally, and other developers have been implementing similar solutions. I thought it would be beneficial to create a standardized class that can be added to DRF and used across our projects.

New Validators

  • MaxFileSizeValidator: Ensures files don't exceed a maximum size (in bytes)
  • MinFileSizeValidator: Ensures files meet a minimum size (in bytes)

Features

  • Customizable error messages and codes
  • Deconstructible for migrations
  • Works with FileField and ImageField
  • Gracefully handles objects without .size attribute

Usage

from rest_framework.validators import MaxFileSizeValidator, MinFileSizeValidator

class FileUploadSerializer(serializers.Serializer):
    file = serializers.FileField(validators=[
        MaxFileSizeValidator(1024 * 1024),  # 1MB max
        MinFileSizeValidator(1024),         # 1KB min
    ])

Implementation

  • Added to rest_framework/validators.py
  • 77 new tests covering unit and integration scenarios
  • Documentation added to docs/api-guide/validators.md
  • All existing tests pass (1577 total)

Error Codes

  • max_file_size - Default for MaxFileSizeValidator
  • min_file_size - Default for MinFileSizeValidator

Add two new validators for enforcing file size constraints on uploaded files:

- MaxFileSizeValidator: Ensures files do not exceed a maximum size (in bytes)
- MinFileSizeValidator: Ensures files meet a minimum size (in bytes)

Both validators:
- Support custom error messages and codes
- Are deconstructible for migrations
- Include comprehensive unit and integration tests
- Work with FileField and ImageField
- Follow DRF conventions and patterns
- Remove top-level PIL import from tests/test_validators.py
- Conditionally import PIL inside image-related tests and skip them if Pillow is unavailable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant