Hi,
I’m struggling to find information about when, and especially to be able to answer when not to override the __init__
method of a class based view (CBV). I could not find anything in the forums, all the post are related to the forms.
Is there a good use case when you would like to override __init__
in a CBV to add specific things?
How would you describe the anti-pattern of overriding __init__
?
To be short, it has been used only to avoid passing arguments to methods in the CBV (too many).
Not that I have ever encountered. Anything I’ve needed to do to change the behavior of a CBV has been able to be done in one of the other methods in the class.
I’m not sure it is an anti-pattern, I’ve just never seen the need. Nor have I ever encountered a case where it was done.
Please clarify.
In most cases, methods like get
, get_queryset
, get_context_data
, etc, work with attributes assigned to the class instance. Any method can add data to that instance for subsequent methods to access.
For example, in DetailView
, the get
method calls get_object
, storing the result in self.object
. All other methods within that view then can access self.object
.
I don’t see how overriding __init__
would provide any benefit here.
The code I stumbled upon was something like:
class MyViewSet:
def __init__(self, *args: Any, **kwargs: Any):
self.data = {}
self.valid = False
self.reference_user = None
# many more variables set
def get_from_things(self, request: Request) -> Response:
# set things
do_something()
process_more()
def do_something(self):
# Use variables defined in __init__
self.valid = ...
self.reference_user = ...
def process_more(self):
# Do more things with the vars from __init__
if self.valid:
...
It’s about declaring local variables in the __init__
(local because Django creates a new class instance for each request) to be used in many methods of the CBV intead of passing around those variables as method’s arguments.
The as_view
method (which is the starting point for all CBVs), calls setup
.
I would override setup
to include this data. That seems to me to be the more appropriate place to do this.