I'm having a bit of difficulty understanding how the python __init__
( ) function works. What I'm trying to do is create a new form in django, and use the uni_form helper to display the form in a custom manner using fieldsets, however I'm passing an argument to the form that should slightly change the layout of the form and I can't figure out how to make this work. Here's my code:
class MyForm(forms.Form):
name = forms.CharField(label=_("Your name"), max_length=100, widget=forms.TextInput())
city = forms.CharField(label=_("Your city"), max_length=100, widget=forms.TextInput())
postal_code = forms.CharField(label=_("Postal code"), max_length=7, widget=forms.TextInput(), required=False)
def __init__(self, city, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if city == "Vancouver":
self.canada = True
if self.canada:
# create an extra uni_form fieldset that shows the postal code field
else:
# create the form without the postal code field
However, the reason this isn't working for me. self.canada never seems to have any value outside of __init__
, and therefore even though I passed that argument to the function I can't use the value in my class. I found a workaround for this, which is to create the form entirely inside __init__
using self.fields, but this is ugly. How do I use self.canada outside of __init__
?