Asif Alamgir
Asif Alamgir

Reputation: 1462

Django: Add another subclass in a class based 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

Is this possible in django?

Upvotes: 0

Views: 1100

Answers (1)

Ian Price
Ian Price

Reputation: 7616

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

Upvotes: 2

Related Questions