Home > database >  best way to validate a user's upload files in django
best way to validate a user's upload files in django

Time:05-31

What is the best way to validate a user's upload files, both in size and type?

CodePudding user response:

from django.core.exceptions import ValidationError

def validate_file_size(value):
    filesize= value.size
    
    if filesize > 10485760:
        raise ValidationError("The maximum file size that can be uploaded is 10MB")
    else:
        return value



class File(models.Model):
    name= models.CharField(max_length=500)
    filepath= models.FileField(upload_to='files/', verbose_name="", validators=[validate_file_size])

    def __str__(self):
        return self.name   ": "   str(self.filepath)

CodePudding user response:

You can also check the file mimetype and its suffix. For example:

from pathlib import Path
from django.conf import settings

def file_validator(value):
    if value.size > settings.MAX_FILE_SIZE:
        raise ValidationError("File is too big.")
    if not Path(str(value)).suffix.strip().lower() in ["list of strings of valid suffix"]:
        raise ValidationError("File does not look like as ....")
    mime_type = mimetypes.guess_type(str(value))[0]
    if mime_type not in ["list of strings of valid mime types"]: # image/png, image/jpeg and etc
        raise ValidationError("Invalid mime type.")
  • Related