mysociety / django-images

Attach images to any Django model, with helpful admin
2 stars 2 forks source link

How can I use the HasImageMixin? #2

Open lfalvarez opened 8 years ago

lfalvarez commented 8 years ago

Hello there: I'm using this mixin as follow, but I'm not entirely sure if I'm doing it right This is the test

def test_organization_has_images(self):
        organization = Organization.objects.create(name='La Cosa Nostra')
        image = Image.objects.create(content_object=organization)
        self.assertEqual(organization.primary_image(), image.image)

And when I run it I get this error:

Traceback (most recent call last):
  File "/home/falvarez/Workspace/votainteligente-portal-electoral/popular_proposal/tests/organization_tests.py", line 15, in test_organization_has_images
    self.assertEqual(organization.primary_image(), image.image)
  File "/home/falvarez/.virtualenvs/vota/src/django-images/images/models.py", line 59, in primary_image
    primary_image_model = self.primary_image_model()
  File "/home/falvarez/.virtualenvs/vota/src/django-images/images/models.py", line 65, in primary_image_model
    primary_images = [i for i in self.images.all() if i.is_primary]
AttributeError: 'Organization' object has no attribute 'images'

So, I decided to write a property for the Organization model

class Organization(PopoloOrganization, HasImageMixin):                                                                   
    _id = models.AutoField(primary_key=True)                                                                             

    @property                                                                                                            
    def images(self):                                                                                                    
        return Image.objects.filter(object_id=self._id)

Which does the job, but I'm not entirely sure if you meant the creation of that property or am I getting it all wrong?

Thanks for this code BTW. :smile:

mhl commented 8 years ago

Hi @lfalvarez - I'm afraid this is very under-documented at the moment, but rather than defining a property like that, you're expected to use django.contrib.contenttypes.fields.GenericRelation instead. So in your definition of the Organization model, you should add:

images = GenericRelation(Image)

Does that work for you? (I'm not quite sure why your property doesn't work, although I'd note that it's generally a good idea to add mixins first in the list of superclasses (though that shouldn't make a difference in this case), and it would need to filter on content_type_id as well.)

lfalvarez commented 8 years ago

Works pefectly! thanks a lot! :sparkles: