Opened 8 years ago

Last modified 4 years ago

#27331 closed New feature

Proposed opt_group argument for ModelChoiceField and ModelMultipleChoiceField — at Version 4

Reported by: Héctor Urbina Owned by: nobody
Component: Forms Version: dev
Severity: Normal Keywords: ModelChoiceField optgroup
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Héctor Urbina)

Hello,

I've just implemented this and I thought It could well be incorporated into Django itself; I guess it's a fairly common feature that one may need on any project.

What I propose is to add an optional opt_group argument to ModelChoiceField and ModelMultipleChoiceField; which indicates the item's field whose value is used to group the choices. It should be used in conjunction with a queryset which is (primarily) sorted by the same field.

Let me show with an example:

class Category(models.Model):
    name = models.CharField(max_length=20)

class Item(models.Model):
    name = models.CharField(max_length=20)
    category = models.ForeignKey(Category)

And in some form's initialization process

field = ModelChoiceField(queryset=Item.objects.order_by('category__name', 'name'), opt_group='category')

field.choices will dynamically collect choices into named groups as a 2-tuple, which the underlying widget should present using optgroup HTML elements.

Change History (4)

comment:1 by Héctor Urbina, 8 years ago

Description: modified (diff)

comment:2 by Tim Graham, 8 years ago

Has patch: unset

At first glance, that looks more appropriate as a widget option since ModelChoiceField isn't required to use a Select widget.

in reply to:  2 comment:3 by Héctor Urbina, 8 years ago

Replying to Tim Graham:

At first glance, that looks more appropriate as a widget option since ModelChoiceField isn't required to use a Select widget.

The default ModelChoiceField's widget (Select) is prepared to understand 2-tuples coming on the field's choices attribute and translates them to optgroups.
ModelChoiceField uses ModelChoiceIterator to generate the choices; that is the actual class that is doing the job on my current implementation. My idea is to include support for optgroup, not require it; I'm updating my proposal to clarify that.

comment:4 by Héctor Urbina, 8 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top