0

I'm using django-imagekit to provide thumbnail versions of uploaded images on my Django models.

I would like to define various thumbnail ImageSpecFields in a mixin that my models can then inherit. However, each model currently has a different name for the ImageField on which its ImageSpecFields would be based.

I've tried this:

from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFit

class ThumbnailModelMixin(models.Model):
    IMAGE_SPEC_SOURCE_FIELD = None

    list_thumbnail = ImageSpecField(
        source=IMAGE_SPEC_SOURCE_FIELD,
        processors=[ResizeToFit((80, 160)],
        format="JPEG",
        options={"quality": 80}
    )

    class Meta:
        abstract = True

class Book(ThumbnailModelMixin):
    IMAGE_SPEC_SOURCE_FIELD = "cover"
    cover = models.ImageField(upload_to="books/")

class Event(ThumbnailModelMixin):
    IMAGE_SPEC_SOURCE_FIELD = "ticket"
    ticket = models.ImageField(upload_to="events/")

But this fails on page load with:

AttributeError: 'Book' object has no attribute 'list_thumbnail'

Is there a way to get inheritance like this to work?

There are at least two other solutions:

  1. Don't use a mixin/parent, and include the ImageSpecFields on each child class - a lot of duplicate code.
  2. Change the Book.cover and Event.ticket fields to have the same name, like image and use "image" for the ImageSpecField source parameter.

The latter sounds best, but I'm still curious as to whether there's a way to get the inheritance working?

Phil Gyford
  • 13,432
  • 14
  • 81
  • 143
  • I ended up doing solution (2), changing the models' image field to `thumbnail`. I'd still like to know if it's possible to get it working otherwise though. – Phil Gyford Apr 07 '20 at 13:34
  • And I suspect it just isn't possible, judging by this similar answer I've finally found https://stackoverflow.com/a/17245249/250962 – Phil Gyford Apr 07 '20 at 15:48

0 Answers0