问题描述
我正在尝试以表单形式使用CheckboxSelectMultiple,而不是SelectMultiple默认形式。我尝试了两种不同的方法使其显示为复选框,但它们均在本地网页上显示默认的SelectMultiple。其他所有内容均可正确呈现({{form.as_table}})。有人会指出我正确的方向吗?谢谢,
Django版本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'
解决方法
您没有使用您构建的表单。您只需构造一个ModelForm
,然后让CreateView
创建另一个ModelForm
,因为您没有指定form_class
[Django-doc]。
因此,您可以更新CreateView
,并使用:
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'