'Django CheckboxSelectMultiple not displaying in ModelForm
I'm trying to use CheckboxSelectMultiple in a form, instead of the SelectMultiple default. I tried two different ways to make it display as checkboxes, but they both display the default SelectMultiple on my local webpage. Everything else renders correctly ( {{ form.as_table }} ). Would someone point me in the right direction? Thanks,
Django version 3.0.2
Python 3.6.9
models.py
class MyModel(models.Model):
m2m = models.ManyToManyField('OtherModel', blank=True)
[...]
forms.py
from django.forms import ModelForm
from myapp.models import MyModel
class MyModelModelForm(ModelForm):
[...]
# I tried this...
m2m = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
class Meta:
model = MyModel
fields = '__all__'
# or this...
widgets = {
'm2m': forms.CheckboxSelectMultiple,
}
views.py
from django.views.generic.edit import CreateView
from myapp.models import MyModel
class MyModelCreate(CreateView):
model = MyModel
fields = '__all__'
template_name = 'MyApp/mymodel_form.html'
Solution 1:[1]
You did not use the form you constructed. You simply constructed a ModelForm
, and then let the CreateView
create another ModelForm
since you did not specify a form_class
[Django-doc].
You can thus update the CreateView
, and work with:
from django.views.generic.edit import CreateView
from myapp.models import MyModel
from myapp.forms import MyModelModelForm
class MyModelCreate(CreateView):
model = MyModel
form_class = MyModelModelForm
template_name = 'MyApp/mymodel_form.html'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |