Home > Mobile >  include text and variable in ValidationError
include text and variable in ValidationError

Time:01-12

I am using this code on the model to check if users are uploading images that are too large

code:

    def validate_image(image):
        file_size = image.file.size
        test = 'whoop'
        if file_size > settings.MAX_UPLOAD_SIZE:
            raise ValidationError("image too large")
image = models.ImageField(default='default.jpg', upload_to=path_and_rename, validators=[validate_image])  

however i want to include the name of the offending file if i use

raise ValidationError(image)

it displays the file name but if I try to include some text

raise ValidationError(image, "is too large")

it will only display whatever comes first either the variable or the string. How can i include both

enter image description here

CodePudding user response:

You can use string formatting to include the text of the image in a string, for example:

def validate_image(image):
    file_size = image.file.size
    if file_size > settings.MAX_UPLOAD_SIZE:
        raise ValidationError(f'Image {image} is too large')
  •  Tags:  
  • Related