Django:在基于类的视图中添加另一个子类

时间:2016-01-24 01:28:39

标签: python django django-class-based-views

这是我的第一个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吗?

1 个答案:

答案 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
相关问题