On Jan 28, 9:04 am, Emiel van de Laar <[email protected]> wrote:
> Hi all,
>
> I've just run into something that I have no idea how to tackle.
> In creating a form with any number of checkboxes I would like
> to share the input control name amongst all the checkboxes.
>
> ~ % cat forms.py
> from django import forms
>
> class FooForm(forms.Form):
>     def __init__(self, *args, **kwargs):
>         super(FooForm, self).__init__(*args, **kwargs)
>
>         for field in ('foo', 'bar'):
>             self.fields[field] = forms.BooleanField()
>
> if __name__ == '__main__':
>     f = FooForm()
>     print(f)
>
> So instead of this output:
>
> ~ % python2.5 ./forms.py                                                      
>                                                                   -- INSERT --
> <tr><th><label for="id_foo">Foo:</label></th><td><input type="checkbox" 
> name="foo" id="id_foo" /></td></tr>
> <tr><th><label for="id_bar">Bar:</label></th><td><input type="checkbox" 
> name="bar" id="id_bar" /></td></tr>
> ...
>
> I would like to see:
>
> ~ % python2.5 ./forms.py                                                      
>                                                                   -- INSERT --
> <tr><th><label for="id_foo">Foo:</label></th><td><input type="checkbox" 
> name="foo" id="id_foo" /></td></tr>
> <tr><th><label for="id_bar">Bar:</label></th><td><input type="checkbox" 
> name="foo" id="id_bar" /></td></tr>
> ...
>
> Notice that the input name attribute needs to be the same for all the input 
> elements (checkboxes).
>
> I've looked through the code but it seems Django forms leans very heavily on 
> the name attribute being unique.
> For HTML checkboxes, however, this is a fairly common technique and the HTML 
> spec allows for it.
>
> Any help would be appreciated. :)
>
> Cheers!
>
>  - Emiel

The HTML you've posted won't work: the form will have no way of
distinguishing between foo and bar, since their HTML names are the
same. If you want multiple checkboxes with the same name, you need to
give them `value` attributes.

In any case, the way to do this in Django is with a
MultipleChoiceField and a CheckboxSelectMultiple widget.
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to