Bug or not? File name length validator.

Hello, i wanted to make a custom validator that validates the length of the name of the file. In this case an image file. I have a custom user model with an ImageField so users can upload their profile picture. In this case the max length of the file name a user can upload is 40 characters.

The validator code:

def validate_image_name_length(value):
    MAX_LENGTH = 40

    if len(value.name) > MAX_LENGTH:
        raise ValidationError(f"File name is too long. It should be at most {MAX_LENGTH} characters.")

When i’m testing this by uploading a profile picture it works fine as long as i stay below 41 characters.
It will validate the length of the name that is being uploaded “len(value.name)” as shown above.

But the problem appears when i’m not changing my profile picture but when i’m changing my username. The username is also in the custom user model.

So when go to the profile settings and i want to change my username and press save, it will give me the image error as shown above. “File name is too long. It should be at most 40 characters.”

When i added a print to the validator i saw that it’s not validating the name anymore but it is validating the name with the whole path to it. And thus exceeding the 40 characters.

For me its kinda weird. When i upload the image, it will validate only the name. But when i’m not changing the image but something else it will validate the whole path of the image plus the name.

What am i doing wrong? Or is it a bug?

Thanks

Hello @olivierthis!

When you upload the file it’s stored in-memory and the .name property points at user provided name during submission while when you are validating an already existing user the .name is the full path of the persisted file referenced by your configured storage.

Try using len(pathlib.Path(value.name).name) instead.

1 Like

Well i never expected the solution to be that simple. Thank you very much!