Skip to content

Instantly share code, notes, and snippets.

@marceloandriolli
Last active August 4, 2021 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marceloandriolli/922cdeb13b9c4f11e16193d1ac2ed383 to your computer and use it in GitHub Desktop.
Save marceloandriolli/922cdeb13b9c4f11e16193d1ac2ed383 to your computer and use it in GitHub Desktop.
Django dynamic Image dimension validator
""""
When you wanna validate dynamically different image size in Django forms and model forms
""""
# settings.py
DEFAULT_THUMBNAILS_DIMENSION = (
os.getenv('THUMBNAIL_WIDTH_PX', 300), os.getenv('THUMBNAIL_HEIGHT_PX', 300)
)
# validators.py
# Factory funciton alternative
from django.core.files.images import get_image_dimensions
def validate_image_max_dimension(image_width=None, image_pixel=None):
"""
This is a factory validation and the default dimesion
could be defined by settings with DEFAULT_THUMBNAILS_DIMENSION
or by var env THUMBNAIL_WIDTH_PX and THUMBNAIL_HEIGHT_PX
"""
def _validate_image_dimension(value):
if not image_width and not image_pixel:
width_pixel, height_pixel = settings.DEFAULT_THUMBNAILS_DIMENSION
else:
width_pixel = image_width
height_pixel = image_pixel
width, height = get_image_dimensions(value)
if width > width_pixel and height > height_pixel:
message = u'Max dimension: {} x {} pixels'.format(
width_pixel, height_pixel
)
raise ValidationError(message)
return _validate_image_dimension
# Class alternative
from django.core.files.images import get_image_dimensions
class ValidateImageMaxDimension:
"""
This is a base class and the default dimesion
could be defined by settings with DEFAULT_THUMBNAILS_DIMENSION
or by var env THUMBNAIL_WIDTH_PX and THUMBNAIL_HEIGHT_PX
"""
width_pixel = None
height_pixel = None
def __init__(self, width=None, height=None):
if width and height:
self.width_pixel = width
self.height_pixel = height
else:
self.width_pixel, self.height_pixel = settings.DEFAULT_THUMBNAILS_DIMENSION
def __call__(self, value):
width, height = get_image_dimensions(value)
if width > self.width_pixel and height > self.height_pixel:
message = u'Max dimension: {} x {} pixels'.format(
self.width_pixel, self.height_pixel
)
raise ValidationError(messag)
#forms.py
from django import forms
from validators import validate_image_max_dimension, ValidateImageMaxDimension
class Myform(forms.ModelForm):
image_1 = forms.ImageField(
validators=[
validate_image_max_dimension(),
],
)
image_2 = forms.ImageField(
validators=[
ValidateImageMaxDimension(width=600, height=600),
],
)
@marceloandriolli
Copy link
Author

imported get_image_dimensions from django

@marceloandriolli
Copy link
Author

typo fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment