选择字段初始数据

时间:2011-11-17 06:07:24

标签: django

我的表格如下。如何选择值?

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')

在上面的例子中,我希望选择尼泊尔。

1 个答案:

答案 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)