我的表格如下。如何选择值?
class ProfileForm(forms.Form):
name = forms.CharField(label=_('Full Name'))
about = forms.CharField(widget=forms.Textarea(), label=_('Tell something about you'))
country = forms.CharField(label=_('Country'), required=False)
def __init__(self, tz_choice=0, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
country_list = Country.objects.all().order_by('name')
country_opt = [('', _('Select'))]
for ct in country_list:
country_opt.append([ct.country_code, ct.name])
self.fields['country'] = forms.ChoiceField(choices=country_opt, initial='NP')
在上面的例子中,我希望选择尼泊尔。
答案 0 :(得分:2)
您可以尝试使用ModelChoiceField
class ProfileForm(forms.Form): name = forms.CharField(label=_('Full Name')) about = forms.CharField(widget=forms.Textarea(), label=_('Tell something about you')) country = forms.ModelChoiceField(label=_('Country'), queryset=Country.objects.all(), required=False,initial=Country.objects.get(code="np").pk)