views:

32

answers:

1

In my project I have a class, NewsItem. Instances of NewsItem act like a wrapper. They can be associated with either an ArtWork instance, or an Announcement instance.

Here's how the NewsItem model looks:

class NewsItem(models.Model):   
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 content_object = generic.GenericForeignKey('content_type', 'object_id')
 date = models.DateTimeField(default=datetime.datetime.now,)
 class Meta:
  ordering = ('-date',)
 def __unicode__(self):
  return (self.title())

In a template I'm dealing with a NewsItem instance, and would like to output a certain bunch of html it it's 'wrapping' an Artwork instance, and a different bunch of html if it's wrapping an Announcement instance. Could someone explain how I can write a conditional to test for this?

My first naive try looked like this:

{% if news_item.content_object.type=='Artwork' %}do this{% else %}do that{% endif %}
+2  A: 

You should use the ForeignKey to content_type, which stores this information.

{% if news_item.content_type.model == 'Artwork' %}
Daniel Roseman
Ah so simple! Thanks very much.
bitbutter