Django framework makes storing image files against your database models easy via the ImageField field type. It does not however provide a way for you to validate the dimensions of this uploaded image.
This is of course important to do, otherwise your application will be hosting oversized images which could cause performance issues for end users.
In order to validate image dimensions at the model level we need to create a custom validator.
Here's the code for our validator:
And here's how we can use that in our `models.py` module:
When our model instance is saved this validator will be invoked and if the image is outside of our desired dimensions then an exception will be raised.
By using Django's built-in `ValidationError` errors will propagate all the way to the frontend of the application (if you're using Django forms linked to your templates).
If you're adding this to your project you may also want the tests ☑️