Luke
Luke

Reputation: 1834

django forms - overriding constructor for changing field type depending by input

I need to overrid the constructor of a form: if I have some value in input, some fields has to be ChoiceField, otherwise they have to be CharField. here's the code:

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)

but this way doesn't work. even if I declare before fields as CharField and then I ovverride them in init, they will not be renderized in template (I got this message: ).

any help?

thanks

Upvotes: 1

Views: 3808

Answers (1)

ilvar
ilvar

Reputation: 5841

You should manipulate self.fields[name] after form creation instead of touching self.field before it. For example, instead of:

self.nazione = forms.ChoiceField(choices = util.get_countries_tuple_list())
super(AnagraficaForm, self).__init__(*args, **kw)

There should be (btw, __init__ should return nothing):

super(AnagraficaForm, self).__init__(*args, **kw)
self.fields['nazione'] = forms.ChoiceField(choices = util.get_countries_tuple_list())

Or, if both fields are the same type, just modify necessary attributes:

self.fields['nazione'].choices = util.get_countries_tuple_list()

Upvotes: 3

Related Questions