Search code examples
djangodjango-templatesdjango-viewsdjango-taggit

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.


Solution

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