Django: Optgroup option groups for Select field widgets

0 Comments

To get your select choices to be grouped, you'll have to do a little trickery.

image

The resultant output in HTML is:

01.<select id="id_choice" name="choice">
02.  <optgroup label="Audio">
03.    <option value="vinyl">Vinyl</option>
04.    <option value="cd">CD</option>
05.  </optgroup>
06.  <optgroup label="Video">
07.    <option value="vhs">VHS Tape</option>
08.    <option value="dvd">DVD</option>
09.  </optgroup>
10.  <option value="unknown">Unknown</option>
11.</select>

This example shows you how to provide a list of hardcoded options and it's straight out of the Django docs.

01.from django import forms
02. 
03.MEDIA_CHOICES = (
04.  ('Audio', (
05.    ('vinyl', 'Vinyl'),
06.    ('cd', 'CD'),
07.  )
08.  ),
09.  ('Video', (
10.    ('vhs', 'VHS Tape'),
11.    ('dvd', 'DVD'),
12.  )
13.  ),
14.  ('unknown', 'Unknown'),
15.)
16. 
17.class ExampleForm(forms.Form):
18.  choice = forms.CharField(widget = forms.Select(choices = MEDIA_CHOICES))

That's it. Now you have the choices grouped in your form.

Now you can feel like a pro until you need dynamic choices!

Tablecloth_trick

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog