March 23, 2010 3 Comments
With a normal Django ChoiceField you can specify choices either as a simple tuple of tuples (value, label pairs) or with an extra level structure to organise the choices into named groups. The Django Select widget will then happily render the choices into html optiongroups.
With a ModelChoiceField you don’t specify the choices directly, you give a queryset of results from the db, which just has a flat structure.
I’ve made a ‘GroupedModelChoiceField’ that allows to output optiongroups based on a field from the model in your queryset. Code is here on djangosnippets… simple as that!