Using a single selection field to choose a category in forms

What happens if you want to show category selection in a form? How will the hierarchy be presented? In django-mptt, there is a special TreeNodeChoiceField form field that you can use to show the hierarchical structures in a selected field. Let's take a look at how to do this.

Getting ready

We will start with the movies app that we defined in the previous recipes.

How to do it...

Let's create a form with the category field and then show it in a view:

  1. In the forms.py file of the app, create a form with a category field as follows:
    # movies/forms.py # -*- coding: UTF-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ ...

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.