[Django]-Django ModelForm CheckBox Widget

16👍

In such a case, the easiest way is to put the choices into a separate model and then use a ManyToMany relationship. After that, you simply override the ModelForm’s widget for that field to use forms.CheckboxSelectMultiple and Django will automatically do the right thing. If you insist to use a CharField, you’ll probably have to do something like this snippet.

@ 2. comment: how are you overriding the widget? This is how I do it and it works flawlessly:

class SomeModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SomeModelForm, self).__init__(*args, **kwargs)
        self.fields['some_field'].widget = forms.CheckboxSelectMultiple()

1👍

I’ve just started to look into widgets assignment with ModelForms. In a lot of examples I’ve seen, piquadrat’s included, the Form’s __ init __ method is overridden.

I find this a little confusing, and just overriding the desired field is more natural for me:

class SomeModelForm(forms.ModelForm):
    some_field = forms.CharField(choices=MEDIA_CHOICES,
                                 widget=forms.CheckboxSelectMultiple)
    class Meta:
        model=SomeModel

Note: I’m using Django 1.1.

👤monkut

0👍

Using piquadrat’s answer worked for me, but needed to add a line to define the queryset for the M2M. See this link.

👤andrea

Leave a comment