本文介绍了如何在ModelForm中使用Forms.ChoiceField()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过使用ModelForm在表单中显示一个下拉列表。我的代码添加如下-
I want to show a dropdownlist in my form by using the ModelForm. My code added below-
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)
)
它没有在表单中显示下拉列表。另外,我希望将选择选择为默认值,并使用空值。我该如何实现呢?
It's not showing dropdownlist in the form. Also, I want "Select" selected as default with empty value. How can I achieve that?
预先感谢!
推荐答案
修改了代码。试试这个:
Modified your code.Try this :
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'}),
}
这篇关于如何在ModelForm中使用Forms.ChoiceField()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!