1

hello how to pass a validator on model field ? how to validate dhe field?

from django.core.validators import validate_image_file_extension

class Photo(models.Model):
    image = models.ImageField('Image', upload_to=image_upload_path, validators=?????)

1 Answers1

2

To use validate_image_file_extension you need to import it from django.core.validators, then you can use it like others validators:

from django.core.validators import validate_image_file_extension

class Photo(models.Model):
    image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image_file_extension])

If a user uploads a file that isn't an image, you will see this message in the error list:

Upload a valid image. The file you uploaded was either not an image or a corrupted image.

To get the error list in the template you have to use this:

{{ form.image.errors }}

Where form is the form object passed to the template.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Alesanco
  • 1,840
  • 1
  • 11
  • 13
  • Is it possible to override or translate the error message? If it is possible, how can I do that? – 14mble Nov 15 '20 at 14:38
  • 1
    Nevermind I made it work! I added an if statement in the view for `image.errors['image']` and redirected with a message. – 14mble Nov 15 '20 at 15:07