avatar
avatar

Reputation: 12485

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

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.

Upvotes: 21

Views: 11425

Answers (2)

user67416
user67416

Reputation:

If you are in a hurry you can also try:

{{context_name.tags.all|join:", "}}

Upvotes: 23

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

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 %}

Upvotes: 37

Related Questions