Django: Add another subclass in a class based view

↘锁芯ラ 提交于 2020-01-17 03:29:25

问题


This is my first django app and I was wondering if it is possible to have a general class which will be extended by all Views. For example

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

Is this possible in django?


回答1:


Order of inheritance is important and calls of super cascade down the line of inheritance. You must account for any variables that may be passed down in inheritance in your __init__ methods.

The first inheritances methods will be called first, and the second as as the __init__ method of the first parent calls super (in order to call the __init__ of the second parent). GeneralParent must inherit from object or a class that inherits from 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


来源:https://stackoverflow.com/questions/34971188/django-add-another-subclass-in-a-class-based-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!