Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 876
user569139 Avatar asked Jan 09 '11 21:01

user569139


1 Answers

Since you have defined the 'bookmarks' GenericRelation field, you can just iterate through that:

{% for bookmark in link.bookmarks.all %}
like image 158
Daniel Roseman Avatar answered Oct 22 '22 06:10

Daniel Roseman