Using categories in templates#
Getting all items within a category#
The Category model automatically gets reverse relationships with all other models related to it.
This allows you access to the related objects from the template without altering any views. For example, if you only had Entry models related to Category, your categories/category_detail.html template could look like
1{% extends 'categories/base.html' %}
2{% block content %}
3<h1>{{ category }}</h1>
4{% if category.parent %}
5 <h2>Go up to
6 <a href="{{ category.parent.get_absolute_url }}">
7 {{ category.parent }}
8 </a></h2>
9{% endif %}
10{% if category.description %}<p>{{ category.description }}</p>{% endif %}
11{% if category.children.count %}
12 <h2>Subcategories</h2>
13 <ul>
14 {% for child in category.children.all %}
15 <li><a href="{{ child.get_absolute_url }}">{{ child }}</a></li>
16 {% endfor %}
17 </ul>
18{% endif %}
19<h2>Entries</h2>
20{% if category.entries_set.all %}
21 {% for entry in category.entries_set.all %}
22 <p><a href="{{ entry.get_absolute_url }}">{{ entry.headline }}</a></p>
23 {% endfor %}
24{% else %}
25 <p><em>No entries for {{ category }}</em></p>
26{% endif %}
27
28{% endblock %}
If you have related_name parameters to the configuration (see Registering Models), then you would use category.related_name.all instead of category.relatedmodel_set.all.