7

I have django ModelForm for model with ManyToManyField. I want to change widget for this field toCheckboxSelectMultiple. Can I do this without overriding a field in a form definition?

I constantly use code similar to this:

class MyModel(ModelForm):
    m2m_field = forms.ModelMultipleChoiceField(queryset = SomeModel.objects.all(),
                                               widget = forms.CheckboxSelectMultiple())

Is there other way to do this?

EDIT: I need this for Django 1.1.1 project

dzida
  • 8,854
  • 2
  • 36
  • 57

2 Answers2

26

If you're using Django 1.2+, you can use the widgets tuple in the inner Meta class.

class MyModelForm(forms.ModelForm):
    class Meta:
        widgets = {'m2m_field': forms.CheckboxSelectMultiple}

See the documentation.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • cool one! Thanks! unfortunetely in this project I use Django 1.1.1 so it won't help, anyway thanks for hint. – dzida Jul 02 '10 at 22:00
7

Another way to do this is doing it in the init of the ModelForm:

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

    [...]
patrick
  • 6,533
  • 7
  • 45
  • 66