我想通过使用ModelForm在我的表单中显示一个下拉列表。我的代码在下面添加了 -
from django import forms
from django.forms import ModelForm
class CreateUserForm(ModelForm):
class Meta:
model = User
fields = ['name', 'age']
AGE_CHOICES = (('10', '15', '20', '25', '26', '27', '28'))
age = forms.ChoiceField(
widget=forms.Select(choices=AGE_CHOICES)
)
它没有在表单中显示下拉列表。另外,我想要"选择"选中为空值的默认值。我怎样才能做到这一点?
提前致谢!
答案 0 :(得分:1)
修改你的代码。试试这个:
from django import forms
from django.forms import ModelForm
class CreateUserForm(ModelForm):
class Meta:
model = User
fields = ('name', 'age')
AGE_CHOICES = (
('', 'Select an age'),
('10', '10'), #First one is the value of select option and second is the displayed value in option
('15', '15'),
('20', '20'),
('25', '25'),
('26', '26'),
('27', '27'),
('28', '28'),
)
widgets = {
'age': forms.Select(choices=AGE_CHOICES,attrs={'class': 'form-control'}),
}