Home > database >  how to display all categories on template in django
how to display all categories on template in django

Time:07-21

I was trying to fetch all the categories on the template but they are repeating because there are multiple lines in database. here is what currently showing

CodePudding user response:

Probably distinct from Django ORM can help:

your_category_queryset = your_category_queryset.distinct() 

or, in template:

{% for category in your_category_queryset.distinct %} 
    {{ category }}
{% endfor %}

More here: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#distinct

CodePudding user response:

Actually, I can't see your codes. So here is an example to solve your problem.

model:

class Category (models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=255, unique=True)

    def __str__(self):
        return self.name

view:

def category(request):
categories = Category.objects.all()
context =  {'categories': categories}
return render (request, 'index.html', context)

index.html:

 <h3>Catagory:</h3>
      <ul>
        {% for category in categories %}
        <li>
            {{category.name}}
          </a>
        </li>
        {% endfor %}
      </ul>
  • Related