Skip to content Skip to sidebar Skip to footer

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

Solution 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

Post a Comment for "Django: Add Another Subclass In A Class Based View"