I’m using Django for our project. And I have created a form using Django forms. In one of the form i need to check a variable and based on the value of the variable i need to add or remove an element.
I’m passing this variable to the form when the object is initialized.
ie form=MyForm(flag)
And in the forms class i’m doing this
class MyInfoForm(forms.Form):
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
super(MyInfoForm, self).__init__(*args, **kwargs)
print self.flag
Firstname = forms.CharField(label=u' First name :', max_length=30)
In the init function i have printed the flag and its working fine. But how can i access the variable out side init
I tried
class MyInfoForm(forms.Form):
myFlag=None
def __init__(self, *args,**kwargs):
self.flag= kwargs.pop('flag', None)
myFlag=self.flag
super(MyInfoForm, self).__init__(*args, **kwargs)
print self.flag
Firstname = forms.CharField(label=u' First name :', max_length=30)
print myFlag
But its not working.
The
classstatement is an executable statement that:type) with the classname, namespace, and list of parent classesclassobject to the classname in the enclosing (usually the module) namespaceTo make a long story short you just cannot access instance attributes from within the
classstatement body, since neither the instance nor even the class itself exist yet.If what you want is to update / add / remove fields on a per instance basis and according to some argument passed to the form’s initializer, the correct solution is to first call the parent’s initializer (to make sure your form’s instance fields are correctly initialized) then do whatever you have to do, ie: