Search code examples
djangomany-to-many

ManytoMany Tags in HTML Template


I'm very new to Django and have the a model with the ManyToMany field. I'm trying to surface the tag names in my html. If I use {{ listing.tag }} in my template I get something like <django.db.models.fields.related.ManyRelatedManager object at 0x10916f410> and {{ listing.tag.name }} doesn't show anything.

Here is my model:

from django.db import models
from django_extensions.db.fields import AutoSlugField

class Tag(models.Model):
    name = models.CharField(max_length=100)
    slug = AutoSlugField(populate_from='name', unique=True)

    def __unicode__(self):
        return self.name

class Listings(models.Model):
    listing = models.CharField(max_length=50)
    description = models.CharField(max_length=500)
    email = models.EmailField(max_length=75)
    tag = models.ManyToManyField(Tag)
    pub_date = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.listing  

How would I show the name of the tag? Thanks in advance.


Solution

  • Since ManyToMany returns a queryset, you need to loop through the queryset.

    You can access the queryset this way: {{ listing.tag.all }}

    and you can access it this way

    {% for tag in listing.tag.all %}
        {{tag.name}}
    {% endfor %}