1

Some parts of my site are branding and the images should only be of particular dimensions.

Is it possible to have the ImageChooser only display images of a certain dimension ?

In a previous question @Alexy showed how the ImageField clean method can be used to only allow certain images Can a wagtail ImageField be restricted to by image dimension

But to be more user friendly, I'd like the ImageChooser to only display suitable images in the first place.

user unknown
  • 35,537
  • 11
  • 75
  • 121
Stuart Axon
  • 1,844
  • 1
  • 26
  • 44

2 Answers2

4

You can create a subclass of ImageChooserBlock, and override the field property of ChooserBlock to filter the images available in the choice field:

from django import forms
from django.utils.functional import cached_property

class SmallImageChooserBlock(ImageChooserBlock):

    @cached_property
    def field(self):
        # Filter the choice field to include only images with 
        # width 100 and height 100
        return forms.ModelChoiceField(
            queryset=self.target_model.objects.filter(width=100, height=100), 
            widget=self.widget, 
            required=self._required, 
            help_text=self._help_text
        )

Then use this block to render the content panel for that field.

solarissmoke
  • 30,039
  • 14
  • 71
  • 73
1

You could rig up something pretty easily using Django's signals to create width/height tags whenever you upload an image. It would look something like this:

# signals.py
from django.db.models.signals import pre_save
from django.dispatch import receiver
from wagtail.images.models import Image


@receiver(pre_save, sender=Image)
def create_image_dimension_tags(sender, **kwargs):
    if kwargs.get('created', False):
        image = kwargs.get('instance')
        height = image.file.height
        width = image.file.width
        image.tags.create(name=f'{height}h')
        image.tags.create(name=f'{width}w')

A 100x100 image would then have a 100w tag and a 100h tag you could use to filter the uploaded images.

Franey
  • 4,164
  • 2
  • 16
  • 18
  • Thanks for having a go at this, I considered something like this, but it seemed like there must be a way using the info already in wagtail, which is what the other answer does. – Stuart Axon Apr 04 '18 at 10:53