views:

952

answers:

2

I have a issue linking content type. I'm trying to pull a title out from this model

class TankProfile(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    tank_type = models.SmallIntegerField(max_length=1, choices=TANK_TYPE, db_index=True, default=1, verbose_name="Tank Type")
    ts = models.DateTimeField(auto_now=True)
    tsStart = models.DateTimeField(auto_now_add=True)
    tsEnd = models.DateTimeField(null=True, auto_now=False, blank=True)
    pic = models.CharField(max_length=25)
    slug = models.CharField(max_length=100)

    def __unicode__(self):
        return str(self.title)

    def get_title(self):
        return "%s" % self.title

My linking model is as follows that uses contenttype

class Photo(models.Model):
    album = models.ForeignKey(Album)
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType, related_name="content_type_set_for_%(class)s")
    object_pk = models.IntegerField(_('object ID'))
    server = models.CharField(max_length=20)
    dir = models.CharField(max_length=20)
    image = models.CharField(max_length=20)
    added = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=150)
    about = models.TextField()


    def get_root_title(self):

        c = ContentType.objects.get(id=self.content_type.id).model_class()
        print c.title

        return "Photos"

    def __unicode__(self):
        return str(self.id)

In the template when I call

{{ photo.get_root_title }}

Nothing shows up.. and nothing gets printed.. what am I doing wrong?

A: 

I don't know why you specifically chose the get_root_title def but normally with django's ORM i'd do that like this

{{ photo.content_type.title }}

and you easily get the title

Rasiel
that doesn't work.. if I use {{ photo.content_type }} i get back a tank profile but if I add .title I get nothing
Mike
+2  A: 

Your c is a class object, it does not have an attribute title.

What you want is an object that is referenced by both content_type and object_id - this is what is actually called generic relation, as described in Django docs. To use it, add the FK to your Photo class:

content_object = generic.GenericForeignKey('content_type', 'object_id')

then you can just use this property in your template using just {{ photo.content_object.title }}.

zgoda