Pass QuerySet of your hierarchical categories to the template and then use the {% recursetree %} template tag as follows:
- Create a view that loads all the categories and passes them to a template:
# movies/views.py
# ...other imports... from django.shortcuts import render
from .models import Category
# ...
class MovieCategoryListView(View):
template_name = "movies/movie_category_list.html"
def get(self, request, *args, **kwargs):
context = {
"categories": Category.objects.all(),
}
return render(request, self.template_name, context)
- Create a template with the following content to output the hierarchy of categories:
{# templates/movies/category_list.html #} {% extends "base.html" %}
{% load mptt_tags %}
{% block content %}
<ul class="root">
{% recursetree categories %}
<li>
{{ node.title }}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
{% endblock %}
- Create a URL rule to show the view:
# movies/urls.py
# ...other imports...
from django.urls import path
from .views import MovieCategoryListView
urlpatterns = [
# ...
path('category/', MovieCategoryListView.as_view(),
name='category_list')
]