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
# ...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)
  1. 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 %}
  1. 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')
]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.90.131