[英]Django/Python - Check if argument was passed to class
I am passing different arguments to a Django form and would like check which argument was passed inside the form's class. 我正在将不同的参数传递给Django表单,并希望检查在表单的类中传递了哪个参数。 How can i do that? 我怎样才能做到这一点?
views.py views.py
...
form = CategoryForm(choose_category =True)
...
forms.py 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__
? 在上面的示例中-错误是name 'self' is not defined
,我如何检查__init__
之外的choose_category
的存在?
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. 这是一个关于python的问题,我如何检查从类内部但在__init__
构造函数外部传递了哪些参数的类。 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 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__
. 这种事情必须在__init__
内部完成。 From there you can add or modify field definitions via the self.fields
dict. 在这里,您可以通过self.fields
字典添加或修改字段定义。
if choose_category:
self.fields['cat'] = forms.ModelChoiceField(queryset=....)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.