Django Crispy Forms and Option Groups

1.4k views Asked by At

I've been searching around on the Crispy Forms documentation as well as general web searching for an answer to this.

Can Crispy Forms output <optgroup>'s within a ChoiceField using the forms.Select widget? Or must I take the data into the context and build the form out the old fashioned way in the template?

Thanks!

2

There are 2 answers

0
RickZ On BEST ANSWER
USER_GENERATED_TEMPLATES = MessageTemplate.objects.filter(Q(client=client_id) | Q(client=None) & Q(user_generated=True))
DEFAULT_TEMPLATES = MessageTemplate.objects.filter(Q(client=client_id) | Q(client=None) & Q(user_generated=False))

# Set the initial TEMPLATE CHOICES list to include the Default Templates choice object
TEMPLATE_CHOICES = [('Default Templates',([[template.id, template.name] for template in DEFAULT_TEMPLATES]))]

# If there are user generated templates, append the TEMPLATE_CHOICES list to include them
if USER_GENERATED_TEMPLATES.count() > 0:
    TEMPLATE_CHOICES.append(('Saved Templates',([[template.id, template.name] for template in USER_GENERATED_TEMPLATES])))

# Set the 'template' form field to a ChoiceField using the Select widget populated by the TEMPLATE_CHOICES list.
self.fields['template'] = forms.ChoiceField(widget = forms.Select(), choices=TEMPLATE_CHOICES)
1
Alasdair On

The choices docs give an example of how you can group your choices.

MEDIA_CHOICES = (
    ('Audio', (
            ('vinyl', 'Vinyl'),
            ('cd', 'CD'),
        )
    ),
    ('Video', (
            ('vhs', 'VHS Tape'),
            ('dvd', 'DVD'),
        )
    ),
    ('unknown', 'Unknown'),
)

If you do this, then the select widget should output optgroups, whether or not you use crispy forms.