Django Categories 1.6 documentation

This Page

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{% extends 'categories/base.html' %}
{% block content %}
<h1>{{ category }}</h1>
{% if category.parent %}
    <h2>Go up to 
        <a href="{{ category.parent.get_absolute_url }}">
            {{ category.parent }}
        </a></h2>
{% endif %}
{% if category.description %}<p>{{ category.description }}</p>{% endif %}
{% if category.children.count %}
    <h2>Subcategories</h2>
    <ul>
        {% for child in category.children.all %}
        <li><a href="{{ child.get_absolute_url }}">{{ child }}</a></li>
        {% endfor %}
    </ul>
{% endif %}
<h2>Entries</h2>
{% if category.entries_set.all %}
    {% for entry in category.entries_set.all %}
        <p><a href="{{ entry.get_absolute_url }}">{{ entry.headline }}</a></p>
    {% endfor %}
{% else %}
    <p><em>No entries for {{ category }}</em></p>
{% endif %}

{% 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.

Template Tags

To use the template tags:

{% import category_tags %}

tree_info

Given a list of categories, iterates over the list, generating two-tuples of the current tree item and a dict containing information about the tree structure around the item, with the following keys:

'new_level'
True if the current item is the start of a new level in the tree, False otherwise.
'closed_levels'
A list of levels which end after the current item. This will be an empty list if the next item’s level is the same as or greater than the level of the current item.

An optional argument can be provided to specify extra details about the structure which should appear in the dict. This should be a comma-separated list of feature names. The valid feature names are:

ancestors

Adds a list of unicode representations of the ancestors of the current node, in descending order (root node first, immediate parent last), under the key 'ancestors'.

For example: given the sample tree below, the contents of the list which would be available under the 'ancestors' key are given on the right:

Books                    ->  []
   Sci-fi                ->  [u'Books']
      Dystopian Futures  ->  [u'Books', u'Sci-fi']