views:

222

answers:

1

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__?

+2  A: 

You have misunderstood the way classes work in Python. You're trying to run code inside a class but outside of any function, which is unlikely to work, especially if it depends on something that happens inside __init__. That code will be evaluated when the class is first imported, whereas __init__ happens when each form is instantiated.

The best way would surely be to include the fieldsets in the form, but simply don't display them when canada is True. Your __init__ code can set those fields to required=False dependent on that value, so you don't get validation errors.

Daniel Roseman
Thanks for the reply Daniel. In retrospect this seems like a pretty amateur question from me, but you're right, I was confused about how classes work. Anyway, I understand what you're suggesting, except I'm not sure how to do it exactly. How do I not display a fieldset when canada is False?
hora
This probably depends on the way you're outputting the form. I don't know much about uni_form - can you show your template?
Daniel Roseman
Oh, OK. I opted not to do display my form in the template, I'm using uni_form to generate it, so I can't do it that way, but now that I know how classes work in Python I can figure out a better way to display my forms. Thanks!
hora