简体   繁体   中英

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'

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 

class MyModelCreate(CreateView):
    model = MyModel
    
    template_name = 'MyApp/mymodel_form.html'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM