Search code examples
djangooopinheritancedjango-viewsdjango-class-based-views

Django CBV: How to subclass scattered parts of code from the parent class


I'm trying to jump from the world of FBV to CBV, but running into an immediate problem...which i'm sure must be pretty common and solvable and I just don't know how...

I'm inheriting the general View class into my parent class, which has all the code from my FBV.

I created a sub-class which inherits from the parent, and the page still loads fine. Good initial start!

But now, I want to utilize the inheritance feature of CBV. I want to move (or override) multiple unique pieces in the parent to the child. I just want to leave the "common" code in the parent, and then all unique things to the child (and eventually other child classes).

For example...I have about 1,000 lines of code in parent. And I will need to move / override probably 1/3 of it into child classes. But that 1/3 is scattered from the beginning to the end of the parent. It's not like the parent will be the complete first 1/2 of the code, and then the child classes will be last 1/2.

Which presents 2 problems...

A) For example, when I want to override a particular section of code in the child, some of the variables necessary to come up with the result of that chunk of code, are in the beginning part of the parent class, which I don't need in the child...It seems like the only way to accomplish this is almost having to copy the entire code in the parent to the child class, which feels like its defeating the purpose of OOP / inheritance / DRY.

B) Because there's bits and pieces I want to override, scattered throughout the parent, I don't know how the code will be able to really know the order to execute...for example...If i'm moving lines 50-100, 340-600, 880-900, to the subclass (because these lines will be different per child class)...I still need the code to really execute them in the original order, in order to be work properly. It almost feels like I need to somehow tell it "do this method in the parent first, then go to the child and do this one, then back to the parent and continue, etc"

Sorry for no code snippets. I think this is more theoretical understanding at this point.

Any help is greatly appreciated!!!


Solution

  • As mentioned by @lhasaDad above, just need to call the methods in order. Note they can be written outside the Post() method, but need to be called in the Post() method!

    enter image description here