更新 1:8 月 10 日
def get_context_data(self, **kwargs):
if "form" in kwargs:
form = kwargs['form']
else:
form = self.get_form()
kwargs['form'] = form
cd = super().get_context_data(**kwargs)
self.form_class()
cd.update({
'matches_list': self.page.object_list,
'form_hidden_fields': list(form.get_hidden_fields()),
})
return cd
这是您可以使用的另一种方法,因为当您调用get_context_data 时,它会创建它不存在的表单。这意味着您要么创建表单,要么让它创建表单。如果继承类的get_context_data 做到了,那么它会在kwargs 中做到,如果没有破解方法,您将无法提取。
原始方法
因此,您可以使用启动类的方法,也可以使用组合方法,其中相同的方法既可以用作类方法,也可以用作实例方法。该技术如下文所示
Creating a method that is simultaneously an instance and class method
下面是相同的演示
import functools
class combomethod(object):
def __init__(self, method):
self.method = method
def __get__(self, obj=None, objtype=None):
@functools.wraps(self.method)
def _wrapper(*args, **kwargs):
if obj is not None:
return self.method(obj, *args, **kwargs)
else:
return self.method(objtype, *args, **kwargs)
return _wrapper
class SpeedyMatchSettingsMiniForm(object):
@combomethod
def get_fields(self):
return ('gender_to_match', 'match_description', 'min_age_to_match', 'max_age_to_match', 'diet_match', 'smoking_status_match', 'relationship_status_match')
@combomethod
def get_visible_fields(self):
return ('diet_match', 'min_age_to_match', 'max_age_to_match')
@combomethod
def get_hidden_fields(self):
fields = self.get_fields()
visible_fields = self.get_visible_fields()
return (field_name for field_name in fields if (not (field_name in visible_fields)))
print(list(SpeedyMatchSettingsMiniForm().get_hidden_fields()))
print(list(SpeedyMatchSettingsMiniForm.get_hidden_fields()))
输出是
['gender_to_match', 'match_description', 'smoking_status_match', 'relationship_status_match']
['gender_to_match', 'match_description', 'smoking_status_match', 'relationship_status_match']
因此,在您的情况下,您可以直接使用 Class 对象