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 these ads

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 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

  2. Steve Jones says:

    Ooops. HTML was escaped in my last comment…

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

    http://dpaste.com/hold/699402/

  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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: