I'm having a bit of difficulty understanding how the python __init__
( ) function works. What I'm trying to do is create a开发者_Python百科 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__
?
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.
精彩评论