开发者

How to change ManyToManyField widget to CheckboxSelectMultiple without overriding field definition in a ModelForm

I have django ModelForm for model with ManyToManyField. I w开发者_高级运维ant 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


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.


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()

    [...]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜