Django: Optgroup option groups for Select field widgets

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


The resultant output in HTML is:

<select id="id_choice" name="choice">
<optgroup label="Audio">
<option value="vinyl">Vinyl</option>
<option value="cd">CD</option>
<optgroup label="Video">
<option value="vhs">VHS Tape</option>
<option value="dvd">DVD</option>
<option value="unknown">Unknown</option>

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

from django import forms

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

class ExampleForm(forms.Form):
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!



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