Django: optiongroups for your ModelChoice Field

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!

3 thoughts on “Django: optiongroups for your ModelChoice Field”

  1. Great snippet. Found this on (newer version Dec ’11).

    When I used this code, it seems to group them into the correct option groups. However, it creates duplicate for the same group_by_field

    e.g. here’s what i’m getting:




    Any ideas on what would be causing this to happen? the groupby() iterator should be able to correctly group the “2”‘s together instead of as two seperate groups.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s