Created
November 30, 2021 05:36
-
-
Save yeazin/69af4b7f22bd77bfbf0ea839ab939dbf to your computer and use it in GitHub Desktop.
Custom File Input Validation in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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