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!


About anentropic
songwriter, musician, and er web programmer...

3 Responses to Django: optiongroups for your ModelChoice Field

  1. Steve Jones says:

    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.


  2. Steve Jones says:

    Ooops. HTML was escaped in my last comment…

    Here is what HTML looks like based on results of using GroupedModelChoiceField()

  3. Steve Jones says:

    Works now.
    Didn’t read your comments well enough. The queryset must be ordered correctly!!!

    Great snippet BTW.

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 )

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: