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?
Since you have defined the 'bookmarks' GenericRelation field, you can just iterate through that:
{% for bookmark in link.bookmarks.all %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With