2013-08-07 79 views
3

我有一個地址表單,它有一個國家的選擇字段。我想在表單加載之前設置一個值。我怎麼能這樣做? 這裏是形式:如何在django中設置choicefield的值

from django import forms 
from django.utils.translation import gettext as _ 

from django_countries import countries 
from core.api import NcpAPI 


class AddressForm(forms.Form): 
    # first_name  = forms.CharField(label=_("First Name"), widget=forms.TextInput(attrs={'class':'form-text required'})) 
    # last_name   = forms.CharField(label=_("Last Name"), widget=forms.TextInput(attrs={'class':'form-text required'})) 
    # company  = forms.CharField(label=_("Company"), widget=forms.TextInput(attrs={'class':'form-text required'})) 
    street   = forms.CharField(label=_("Street/PoBox"), widget=forms.TextInput(attrs={'class':'form-text required'})) 
    address1  = forms.CharField(label=_("Address1"), widget=forms.TextInput(attrs={'class':'form-text required'})) 
    address2  = forms.CharField(required=False, label=_("Address2"), widget=forms.TextInput(attrs={'class':'form-text'})) 
    address3  = forms.CharField(required=False, label=_("Address3"), widget=forms.TextInput(attrs={'class':'form-text'})) 
    city   = forms.CharField(label=_("City"), widget=forms.TextInput(attrs={'class':'form-text required'})) 
    postal_code  = forms.CharField(label=_("Postal code"), widget=forms.TextInput(attrs={'class':'form-text required'})) 
    country   = forms.ChoiceField(label=_("Country"), choices=countries.COUNTRIES, widget=forms.Select()) 

回答

2
country = forms.ChoiceField(label=_("Country"), 
      choices=countries.COUNTRIES, widget=forms.Select(), initial= 'us') 

或致電形式構造

form = AddressForm(initial={'country': 'us'}) 
+0

更多mantainable時,你可以啓動它:__forms.ChoiceField(標籤= _( 「國家」),選擇=國家.COUNTRIES,widget = forms.Select(),default = countries.COUNTRIES [0])__例如,如果有一天你的選擇發生改變,Django不會崩潰:) – Ricola3D

+0

@ Ricola3D默認爲模型,初始 – suhailvs

+0

@suhail,你的代碼不會在我的工作,因爲我正在使用會話嚮導。對不起,我忘了提到這一點。 – Maverick

相關問題