0

I want to use ImageSpecField of django-imagekit for resizing image, so I don't want to create a new ImageSpecField field for every ImageField in my models, I want to create a new class or modelField which contains original image and image thumbnail and instantiate this new modelField in my models for images.

for example if my model has profile_picture field, I want to have both profile_picture and profile_picture_thumbnail. If my model has avatar field I want to have both avatar and avatar_thumbnail

So is there any way to dynamically generate these fields for models?

What is the best approach to do that?

kianoosh
  • 610
  • 6
  • 22

1 Answers1

1

As far as I know, Dynamically injecting fields to a django model is not an easy task. If you want to try , this can be a starting point for you.

Similar post can be found here. http://www.sixpearls.com/blog/2013/feb/django-class_prepared-signal/

from django.db.models.signals import class_prepared
def add_image_fields(sender, **kwargs):
    """
    class_prepared signal handler that checks for the model massmedia.Image
    and adds sized image fields
    """
    if sender.__name__ == "Image" and sender._meta.app_label == 'massmedia':
        large = models.ImageField(upload_to=".", blank=True, verbose_name=_('large image file'))
        medium = models.ImageField(upload_to=".", blank=True, verbose_name=_('medium image file'))
        small = models.ImageField(upload_to=".", blank=True, verbose_name=_('small image file'))

        large.contribute_to_class(sender, "large")
        medium.contribute_to_class(sender, "medium")
        small.contribute_to_class(sender, "small")

class_prepared.connect(add_image_fields)

which basically attach a function to create those fields.

You can catch class_prepared signal and list all fields, if its a image field, then contribute to class image_field_thumbnail

To get all the fields belongs to a model , you can use get_fields

durdenk
  • 1,590
  • 1
  • 14
  • 36