Django:在基于类的视图中添加另一个子类 [英] Django: Add another subclass in a class based view

查看:118
本文介绍了Django:在基于类的视图中添加另一个子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个django应用程序,我想知道是否有可能有一个通用类将被所有View扩展。例如,

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

在Django中有可能吗?

Is this possible in django?

推荐答案

继承的顺序很重要,并且超继承的调用沿继承的方向进行。您必须考虑在您的 __ init __ 方法中可能在继承中传递的任何变量。

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.

第一个继承方法将首先被调用,第二个被称为第一个父调用的 __ init __ 方法超级(以调用第二个父对象的 __ init __ )。 GeneralParent 必须继承自 object 或继承自 object 。

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

这篇关于Django:在基于类的视图中添加另一个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆