Yehuda
Yehuda

Reputation: 133

how to render django-taggit common tags in template

I've seen a lot of questions and answers about how to get most common tags using django-taggit. However that's not really my issue. My issue is how to pass that common tags to my django templates.

To return all tags I had:

{% for tag in model.tags.all %}
   <p>{{tag}}</p>
{% endif %}

And that worked fine. But how do I return the common tags in the template? To get the common tags I have this:

class Home(ListView):
    model = Model
    template_name = 'home.html'

    def get_common_tags(self):
        common_tags = Model.tags.most_common()[:2]
        return common_tags

But how do I access these common_tags? Do I need to get the common tags from the template or should I be passing them from the view?

Upvotes: 0

Views: 254

Answers (1)

Maxim Danilov
Maxim Danilov

Reputation: 3350

it is better to read about Django GCBV.

in your case:

class Home(ListView):
    model = Model
    template_name = 'home.html'

    ...

    def get_context_data(self, **kwargs):
        kwargs['common_tags'] = self.get_common_tags()
        return super().get_context_data(**kwargs)

here we override get_context_data, to get in template variable common_tags https://docs.djangoproject.com/en/4.0/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_data

after that, in template: ¶

{% for tag in model.tags.all %}
   <p>{{tag}}</p>
{% endif %}
   <p> Most common tag are: {{ common_tags }}</p>

common_tags - is a list, you can made something with django template filter, like join:

{{ common_tags|join:" ," }}

or unordered_list:

 <ul>{{ common_tags|unordered_list }}</ul>

more - here: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#unordered-list

Upvotes: 1

Related Questions