Here’s my “quick reference” on the Django ListView method execution order and how to override them:
__init__()
Standard when instance of class is created
setup()
Initializes: self.request, self.args, and self.kwargs
Overriding this method allows mixins to setup instance attributes for reuse in child classes. When overriding this method, you must call super().
dispatch()
Re-directs at GET to get(), POST to post(), etc.
http_method_not_allowed()
Called only when dispatch() cannot properly dispatch to GET
get()
Calls methods in the following order:get_template_names()
Simple method that gets either (but not both):
– the template_name from a variable
– the object modelnameget_queryset()
Gets the queryset; must be an iterableget_context_object_name()
Simple method that gets either:
– the template_name from a variable context_object_name
– the object model_name appended with _list
get_context_data()
Sets the viewbag/dictionary for the Jinja template render_to_response()
This is called last using return keyword to return a “response_class” instance to dispatch()
Important Notes: if you override get(), you must explicitly call get_queryset() and get_context_data() in your own version of get(). You might also need to implement both methods as well.
You can implement any or all 4 methods, but you aren’t required to override get(). The dispatch() method will do that.
The most common configuration is to implement your own get_queryset() and (sometimes) implement get_context_data() calling the super() method first. The custom get_context_data() method allows you to “tack on” extra context.
See the official Django ListView docs for more details: https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-display/#listview