Skip to content

Instantly share code, notes, and snippets.

@yeazin
Created November 30, 2021 05:36
Show Gist options
  • Save yeazin/69af4b7f22bd77bfbf0ea839ab939dbf to your computer and use it in GitHub Desktop.
Save yeazin/69af4b7f22bd77bfbf0ea839ab939dbf to your computer and use it in GitHub Desktop.
Custom File Input Validation in Django
from django.core.exceptions import ValidationError
'''
Custom file validation function
'''
def ValidFile(value):
'''
1 mb = 1,048,576 bytes
15 mb = 15728640 bytes
'''
import os
ext = os.path.splitext(value.name)[1]
filetype = ['.pdf','.docs','.odt','.docx']
if ext.lower() in filetype:
if value.size > 15728640:
raise ValidationError ('Sorry File size max upload 15MB')
else:
return value
else:
raise ValidationError ('Sorry file type not Supported')
from django.db import models
# import your custom file format module
from .fileformat import ValidFile
class FileUplaod (models.Model):
'''
using the module in models
'''
files = models.FileField(null=True,upload_to='files/',blank=True,validators=[ValidFile])
def __str__(self):
return self.files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment