2011-11-17 87 views
1

我有像下面的表格。我如何獲得選定的值?選擇字段初始數據

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

這就是你究竟是如何做到這一點。 'initial'。那裏是一個價值「NP」的國家嗎?我只是測試了這個,它的工作原理...'MyChoiceField.initial ='whatever'' –

+0

是的國家NP是在選擇名單。我嘗試了幾個國家,但沒有奏效。 – Elisa

回答

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) 

+0

如何將其呈現給模板,即此選項標記中的初始值必須顯示選中 – Chipmunk