我需要重写表单的构造函数:如果我在输入中有一些值,则某些字段必须是 ChoiceField,否则它们必须是 CharField。这是代码:
class AnagraficaForm(forms.Form):
usertype = ((1,'Privato'),(0,'Libero professionista/Azienda'))
nome = forms.CharField(max_length=100)
cognome = forms.CharField(max_length=100)
telefono = forms.CharField(max_length=50,required=False)
email= forms.EmailField(max_length=100,required=False)
indirizzo = forms.CharField(max_length=100)
nazione = forms.ChoiceField(choices = util.get_countries_tuple_list())
provincia = forms.CharField(max_length=100)
citta = forms.CharField(max_length=100)
cap = forms.CharField(max_length=10)
codfisc = ITSocialSecurityNumberField(required=False)
piva = ITVatNumberField(required=False)
ragsociale = forms.CharField(max_length=100,required=False)
is_privato = forms.TypedChoiceField(
initial=1,
coerce=lambda x: bool(int(x)),
choices=usertype,
#using custom renderer to display radio buttons on the same line
widget=forms.RadioSelect(renderer=HorizRadioRenderer, attrs={"id":"is_privato"})
)
def __init__(self, country_name = 'ITALIA', region_name = 'MILANO', city_name = 'MILANO', zipcode = '', *args, **kwargs):
if country_name != 'ITALIA':
print 'in if'
self.nazione = forms.ChoiceField(choices = util.get_countries_tuple_list())
self.provincia = forms.CharField(max_length=100, initial = region_name)
self.citta = forms.CharField(max_length=100, initial = city_name)
self.cap = forms.CharField(max_length=10, initial = zipcode)
kw = {'initial':{'nazione': util.get_country_id(country_name)}}
kw.update(kwargs)
return super(AnagraficaForm, self).__init__(*args, **kw)
else:
print 'in else'
self.nazione = forms.ChoiceField(choices = util.get_countries_tuple_list())
self.provincia = forms.ChoiceField(choices = util.get_regions_tuple_list(util.get_country_id(country_name)))
self.citta = forms.ChoiceField(choices = util.get_cities_tuple_list(util.get_country_id(country_name), util.get_region_code(region_name)))
self.cap = forms.ChoiceField(choices = util.get_zips_tuple_list(util.get_country_id(country_name), util.get_region_code(region_name), city_name))
initial = {
'nazione' : 'IT',
'provincia' : util.get_region_code(region_name),
'citta' : util.get_region_from_cityname(city_name),
'cap' : util.get_city_id(zipcode)
}
kw = {'initial': initial}
kw.update(kwargs)
return super(AnagraficaForm, self).__init__(*args, **kw)
但这种方式行不通。即使我在字段之前声明为 CharField 然后在init中覆盖它们,它们也不会在模板中呈现(我收到此消息:)。
有什么帮助吗?
谢谢