Skip to content

Instantly share code, notes, and snippets.

@ag-castro
Created December 24, 2018 03:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ag-castro/88bd803a43ed80f978453d76b4e7b890 to your computer and use it in GitHub Desktop.
Save ag-castro/88bd803a43ed80f978453d76b4e7b890 to your computer and use it in GitHub Desktop.
A validator image for Wagtail CMS
import os
from django.core.exceptions import ValidationError
from django.core.files.images import get_image_dimensions
from django.utils.deconstruct import deconstructible
from wagtail.images.models import Image # To get the image object from wagtail collections
@deconstructible
class ImageValidator:
"""ImageField dimensions validator."""
def __init__(self, width=None, height=None,
min_width=None, max_width=None,
min_height=None, max_height=None,
file_path=None, folder_name=None):
"""
Constructor
Args:
width (int): exact width
height (int): exact height
min_width (int): minimum width
min_height (int): minimum height
max_width (int): maximum width
max_height (int): maximum height
"""
self.width = width
self.height = height
self.min_width = min_width
self.max_width = max_width
self.min_height = min_height
self.max_height = max_height
self.file_path = file_path
self.folder_name = folder_name
def __call__(self, image):
img = Image.objects.get(id=image) # Getting the image object from wagtail collections
w, h = get_image_dimensions(img.file)
ext = os.path.splitext(img.filename)[1]
valid_extensions = ['.png', '.jpg', '.jpeg']
if not ext.lower() in valid_extensions:
raise ValidationError('This file is not a valid image.')
if self.width is not None and w != self.width:
raise ValidationError(
f'({img.filename} - Width: {w}px, Height: {h}px) - '
f'The width image must be {self.width}px'
)
if self.height is not None and h != self.height:
raise ValidationError(
f'({img.filename} - Height: {h}px, Width: {w}px) - '
f'The height image must be {self.height}px '
)
if self.min_width is not None and w < self.min_width:
raise ValidationError(
f'{img.filename} the min width image must be {self.max_width}px '
)
if self.min_height is not None and h < self.min_height:
raise ValidationError(
f'{img.filename} the min height image must be {self.height}px '
)
if self.max_width is not None and w > self.max_width:
raise ValidationError(
f'{img.filename} the max width image must be {self.max_width}px '
)
if self.max_height is not None and h > self.max_height:
raise ValidationError(
f'{img.filename} the max height image must be {self.max_height}px '
)
@ag-castro
Copy link
Author

Then import ImageValidator:
`
from django.db import models
from wagtail.core.models import Page
from .image_validator import ImageValidator

class MyPage(Page):
header = models.OneToOneField(
'wagtailimages.Image',
on_delete=models.SET_NULL,
validators=[ImageValidator(width=1370, height=385)], # Set the params to validation!
related_name='main_image'
)

`

@jpbeltrami
Copy link

Thanks a lot for this, I'll try it out

@jpbeltrami
Copy link

Seems to work..
You might want to change min_width and min_height validation message to this:

        if self.min_width is not None and w < self.min_width:
            raise ValidationError(
                f'{img.filename} the min width image must be {self.min_width}px '
            )

        if self.min_height is not None and h < self.min_height:
            raise ValidationError(
                f'{img.filename} the min height image must be {self.min_height}px '
            )

@jpbeltrami
Copy link

@ag-castro, why not support gif?

@morufajibike
Copy link

I really appreciate this script. Just exactly what I needed. Cheers mate

@flyingwip
Copy link

How would this work in a model that extends AbstractImage?

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