The Django forms API have two field types to work with multiple options:
Both use select input as the default widget and they work in a similar way, except that
ModelChoiceField is designed
to handle QuerySets and work with foreign key relationships.
A basic implementation using a
ChoiceField would be:
Grouped Choice Field
You can also organize the choices in groups to generate the
<optgroup> tags like this:
Grouped Model Choice Field
When you are using a
ModelChoiceField unfortunately there is no built-in solution.
Recently I found a nice solution on Django’s ticket tracker, where
someone proposed adding an
opt_group argument to the
While the discussion is still ongoing, Simon Charette proposed
a really good solution.
Let’s see how we can integrate it in our project.
First consider the following models:
So now our category instead of being a regular choices field it is now a model and the
Expense model have a
relationship with it using a foreign key.
If we create a
ModelForm using this model, the result will be very similar to our first example.
To simulate a grouped categories you will need the code below. First create a new module named fields.py:
And here is how you use it in your forms:
Because in the example above I used a self-referencing relationship I had to add the
exclude(parent=None) to hide
the “group categories” from showing up in the select input as a valid option.
You can download the code used in this tutorial from GitHub: github.com/sibtc/django-grouped-choice-field-example
Credits to the solution Simon Charette on Django Ticket Track.