django-taggit - how do I display the tags related to each record
Asked Answered
P

2

21

I'm using django-taggit on one of my projects and I'm able to save and tie the tags with specific records. Now the question is how do I display the tags related to each record?

For example on my page I want to display a record which contains a title and content and then under it I want to show the tags tied to that record.

What goes in the views.py, and mytemplate.html? Real examples would be truly appreciated.

Pentup answered 7/6, 2011 at 12:35 Comment(0)
M
37

models.py

from django.db import models
from taggit.managers import TaggableManager

class MyObject(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    tags = TaggableManager()

views.py

from django.views.generic import simple

def show_object(request):
    """ View all objects """
    return simple.direct_to_template(request,
        template="folder/template.html",
        extra_context={
            'objects':MyObject.objects.all(),
        }) 

template.html

{% for object in objects %}
    <h2>{{ object.title }}</h2>
    <p>{{ object.content }}</p>
    <ul>
        {% for tag in object.tags.all %}
            <li> {{ tag.name }} </li>
        {% endfor %}
    </ul>
{% endfor %}
Marylandmarylee answered 7/6, 2011 at 13:7 Comment(3)
this will create an additional db query for each object that you have. if you have a lot of objects, that can really slow things down. I've run into that and am looking for a solution.Mabelmabelle
I'm a bit late replying @Mabelmabelle but yes you are right. It could be reduced by making use of preselect_related to prefetch the tags up frontGeology
from django.views.generic import simple is not working for me. Is this module deprecated ?Emulsify
H
22

If you are in a hurry you can also try:

{{context_name.tags.all|join:", "}}
Hearsh answered 12/10, 2014 at 6:21 Comment(1)
This was exactly what I needed.Ammamaria

© 2022 - 2024 — McMap. All rights reserved.