beni
beni

Reputation: 3029

ModelForm in template with a grouped choice field

I have a grouped category field. The problem is that I've created a search form, but when I try presente the form to the user in the template, it goes wrong.

models.py

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

category = models.CharField(max_length=20, choices=MEDIA_CHOICES, verbose_name=_(u'Category'))

forms.py (search)

class SearchingForm(forms.Form):

    "Search Box"
    search = forms.CharField(max_length=100, required=False, label=(_(u'Search')))

    music_kind = forms.MultipleChoiceField(choices=MEDIA_CHOICES, required=False,
                                        label=(_(u'Kind')),    
                                        widget=forms.CheckboxSelectMultiple(),
                                        )

template.html

    {{ form.search }}
    {{ form.place_kind }}

I show the form to the user like this, the problem is when I rendered with a browser I have something like this (in each line, it has a checkbox):

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

I have delete the 'widget=forms.CheckboxSelectMultiple()' attribute it goes right, but I don't have a checkboxes. So, How I can do it with checkbox fields?

Upvotes: 0

Views: 622

Answers (2)

second
second

Reputation: 28637

I'm not sure, but I wonder if choice groups are only for select boxes (not checkboxes).

Upvotes: 1

Brandon Taylor
Brandon Taylor

Reputation: 34573

I think you have a data type mismatch here. You're wanting to store multiple values in a single CharField. Sure, you could save a dictionary of key-value pairs in there, but then you'd have to parse it back out into selections, and that's a huge pain.

I would move your MEDIA_CHOICES to a database table, and then in your SearchingForm, you can do a CheckboxSelectMultiple, and the form will behave as expected.

Upvotes: 1

Related Questions