Django CheckboxSelectMultiple 不显示在 ModelForm 中
Django CheckboxSelectMultiple not displaying in ModelForm
我正在尝试在表单中使用 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 <b>MyModelModelForm</b>
class MyModelCreate(CreateView):
model = MyModel
<b>form_class = MyModelModelForm</b>
template_name = 'MyApp/mymodel_form.html'
我正在尝试在表单中使用 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 <b>MyModelModelForm</b>
class MyModelCreate(CreateView):
model = MyModel
<b>form_class = MyModelModelForm</b>
template_name = 'MyApp/mymodel_form.html'