Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 235
dzida Avatar asked Jul 02 '10 17:07

dzida


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is the super class of Django form?

Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears. It is similar to the ModelForm class that creates a form by using the Model, but it does not require the Model.

What is widget in Django forms?

A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .

What does form Save Do Django?

form. save() purpose is to save related model to database, you are right. You're also right about set_password , for more info just read the docs. Django knows about model and all it's data, due to instance it's holding (in your case user ).


2 Answers

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.

like image 141
Daniel Roseman Avatar answered Nov 01 '22 08:11

Daniel Roseman


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

    [...]
like image 39
patrick Avatar answered Nov 01 '22 08:11

patrick