Rendering categories in a template

Once you have created categories in your app, you need to display them hierarchically in a template. The easiest way to do this is to use the {% recursetree %} template tag from the django-mptt app. I will show you how to do that in this recipe.

Getting ready

Make sure that you have the Category model created and some categories entered in the database.

How to do it...

Pass QuerySet of your hierarchical categories to the template and then use the {% recursetree %} template tag as follows:

  1. Create a view that loads all the categories and passes them to a template:
    # movies/views.py # -*- coding: UTF-8 -*- from __future__ import unicode_literals from django.shortcuts import render from .models import Category def movie_category_list(request): ...

Get Django: Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.