I'm using django-imagekit to provide thumbnail versions of uploaded images on my Django models.
I would like to define various thumbnail ImageSpecField
s in a mixin that my models can then inherit. However, each model currently has a different name for the ImageField
on which its ImageSpecField
s 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:
- Don't use a mixin/parent, and include the
ImageSpecField
s on each child class - a lot of duplicate code. - Change the
Book.cover
andEvent.ticket
fields to have the same name, likeimage
and use"image"
for theImageSpecField
source
parameter.
The latter sounds best, but I'm still curious as to whether there's a way to get the inheritance working?