How can I traverse a reverse generic relation in a Django template?

Posted by user569139 on Stack Overflow See other posts from Stack Overflow or by user569139
Published on 2011-01-09T21:36:02Z Indexed on 2011/01/09 22:53 UTC
Read the original article Hit count: 169

Filed under:
|
|

I have the following class that I am using to bookmark items:

class BookmarkedItem(models.Model):
     is_bookmarked = models.BooleanField(default=False)
     user = models.ForeignKey(User)
     content_type = models.ForeignKey(ContentType)
     object_id = models.PositiveIntegerField()
     content_object = generic.GenericForeignKey()

And I am defining a reverse generic relationship as follows:

class Link(models.Model):
    url = models.URLField()
    bookmarks = generic.GenericRelation(BookmarkedItem)

In one of my views I generate a queryset of all links and add this to a context:

links = Link.objects.all()
context = {
     'links': links
}
return render_to_response('links.html', context)

The problem I am having is how to traverse the generic relationship in my template. For each link I want to be able to check the is_bookmarked attribute and change the add/remove bookmark button according to whether the user already has it bookmarked or not. Is this possible to do in the template? Or do I have to do some additional filtering in the view and pass another queryset?

© Stack Overflow or respective owner

Related posts about django

Related posts about generic