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 djangosnippets.org (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:

    select1
    select2

    select3
    select4
    select5

    select6
    select7
    select8

    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.

    -Steve

Leave a reply to Steve Jones Cancel reply