这是我的第一个django应用程序,我想知道是否可以有一个将被所有视图扩展的通用类。例如
class GeneralParent:
def __init__(self):
#SETTING Up different variables
self.LoggedIn = false
def isLoggedIn(self):
return self.LoggedIn
class FirstView(TemplateView):
####other stuff##
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
allLeads = len(self.getAllLeads())
context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD###
return context
class SecondView(FormView):
####other stuff##
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
allLeads = len(self.getAllLeads())
context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD###
return context
这可能在django吗?
答案 0 :(得分:2)
继承顺序非常重要,并且在继承行中调用超级级联。您必须考虑在__init__
方法中可能在继承中传递的任何变量。
首先调用第一个继承方法,第二个调用第一个父节点的__init__
方法调用super(为了调用第二个父节点的__init__
)。 GeneralParent
必须继承自object
或继承自object
的类。
class GeneralParent(object):
def __init__(self,*args,**kwargs):
#SETTING Up different variables
super(GeneralParent,self).__init__(*args,**kwargs)
self.LoggedIn = false
def isLoggedIn(self):
return self.LoggedIn
class FirstView(GeneralParent,TemplateView):
####other stuff##
def get_context_data(self, **kwargs):
context = super(FirstView, self).get_context_data(**kwargs)
allLeads = len(self.getAllLeads())
context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD###
return context
class SecondView(GeneralParent,FormView):
####other stuff##
def get_context_data(self, **kwargs):
context = super(SecondView, self).get_context_data(**kwargs)
allLeads = len(self.getAllLeads())
context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD###
return context