Search code examples
djangodjango-taggit

How to use django-taggit similar_objects() with Class-based views


I want to display 4 related item on my template which have the same tags as the current item. I'm using the greate package django-taggit and I have read django-taggit doc

and they didn't explain how to use "similar_objects() " to make related item with Class-based views

my views.py:

class GameDetail(DetailView):
    model = Game
    template_name = 'core/game_detail.html'
    context_object_name = 'game_detail'

my models.py :

class Game(models.Model):
    name = models.CharField(max_length=140)
    developer = models.CharField(max_length=140)
    game_trailer = models.CharField(max_length=300, default="No Trailer")
    game_story = models.TextField(default='No Story')
    tags = TaggableManager()

my template "game_detail.html" is very long to post it here if you just can explain how to use django-taggit in my view and how to display the related item on template I'll be grateful


Solution

  • You could build your view this way:

    class GameDetail(DetailView):
        model = Game
        template_name = 'core/game_detail.html'
        context_object_name = 'game_detail'
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context["related_items"] = self.object.tags.similar_objects()[:4]
            return context
    

    Then you can use the related_items list on your template, like you normally do.

    Note: if you are using python2 the super call should be this one:

    context = super(self, GameDetail).get_context_data(**kwargs)