I am passing different arguments to a Django form and would like check which argument was passed inside the form's class. How can i do that?
views.py
...
form = CategoryForm(choose_category =True)
...
forms.py
class CategoryForm(forms.Form):
def __init__(self, *args, **kwargs):
self.choose_category = kwargs.pop('choose_category',None)
super(CategoryForm,self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
if not self.choose_category:
self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success'))
if self.choose_category:
do something
In the example above- the error is that name 'self' is not defined
, how can i check for the existence of choose_category
outside of __init__
?
This is rather a question of python, how can i check which parameters have been passed to a class from inside the class but outside of the __init__
constructor. Also an answer such as - you cannot, it's stupid - is welcome if i get to understand the logical fracture i'm making:)
Thank you!
EDIT: forms. py
Can't understand why this does not work and the fields don't display:
class CategoryForm(forms.Form)
def __init__(self, *args, **kwargs):
self.choose_category = kwargs.pop('choose_category',None)
super(CategoryForm,self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
if not self.choose_category:
self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success'))
self.onchange(False)
else:
self.onchange(True)
def onchange (self, val):
if val:
category = forms.ModelChoiceField(
queryset =Categories.objects.all(),
widget = forms.Select(attrs = {'onchange':'form.submit();'}) ,
empty_label= None,
required=True
)
print('why doesnt it work this way')
else:
category = forms.ModelChoiceField(queryset =Categories.objects.all() ,empty_label= None,required=True)
This sort of thing has to be done inside __init__
. From there you can add or modify field definitions via the self.fields
dict.
if choose_category:
self.fields['cat'] = forms.ModelChoiceField(queryset=....)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.