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
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the 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.
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> .
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 ).
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()
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With