0

For some reason I get an error once I try to apply ImageKit onto a model to create a thumbnail for an ImageField. I am using the ImageKit library for Django which you can find here

My code is below :

from django.db import models
from PIL import Image
import os
from django.contrib import admin
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill

# Create your models here.
class ResidentialReference(models.Model):
    image = models.ImageField(upload_to='images', blank="true",null="true")
    thumbnail = ImageSpecField(source='image',
                               processors=[ResizeToFill(100,50)],
                               format='JPEG',
                               options={'quality':60})

    title = models.CharField(max_length = 1000, default = 'Title here...' )
    postcode = models.TextField(max_length = 1000, default='Postcode here...')
    description = models.TextField(max_length = 12000, default = 'Technical Description here...')
    equipment = models.TextField(max_length = 1000, default = 'Equipment here...')
    output = models.TextField(max_length = 1000, default = 'Rated Output here...')
    partnership = models.TextField(max_length = 12000, default = 'Viessmann partnership details here...')



    def __unicode__(self):
        return self.title

    def create_thumb(self):
        residentialReference = ResidentialReference.objects.all()[0]
        print residentialReference.thumbnail.url
        print residentialReference.thumbnail.width
AndroidKrayze
  • 349
  • 2
  • 5
  • 21

1 Answers1

5

This error doesn't have anything to do with ImageKit.

You're trying to reference the class inside its own definition. That code will be executed when the class is being defined, at which point ResidentialReference doesn't exist.

Put that code into a method, or take it out of the class altogether.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thank you so Much for your quick and correct answer! Works perfectly now. All i had to do is copy that code under def__unicode__(self). – AndroidKrayze Apr 29 '15 at 11:04
  • 2
    Uhhh...I don't think that's what you want to do either @AndroidKrayze. – rnevius Apr 29 '15 at 11:27
  • Moving the problematic line below the __unicode__ function in your code snippet will define an attribute on the ResidentialReference model. However it's probably not what you really intend because the statement will execute only once, whenever the model is instantiated. That's problematic for 2 reasons: a) the value is potentially stale by the time it is referenced, b) it's probably going to lead to unnecessary database reads. – Dwight Gunning Apr 29 '15 at 12:30
  • I see, so in that case I should create another method within that model? – AndroidKrayze Apr 29 '15 at 13:03
  • I have edited the code snippet above. Is that acceptable now? Also code works perfectly! – AndroidKrayze Apr 29 '15 at 13:23