[Fixed]-Django class-based views function execution order

16👍

This DjangoProject page on Generic Display Views seems to be the most helpful, imo.

It covers both ListView and DetailView and explains in detail the methods executed in a class-based display view — Here’s an example of DetailView methods called:

setup()
dispatch()
http_method_not_allowed()
get_template_names()
get_slug_field()
get_queryset()
get_object()
get_context_object_name()
get_context_data()
get()
render_to_response()

3👍

Actually, you’re really doing it upside down. Instead of a central ClubView, it’s more flexible to have one view class for each of the individual actions/pages. E.g., you might have something like this:

class ClubListView(ListView):
    model = Club

class ClubDetailView(DetailView)
    model = Club

# etc...

This way you only need to override specific functionality unique to each of those actions, by defining a particular method on the view class which does what you need. E.g. you need to filter the possible Clubs in the ClubListView dynamically, based on something from the request? Just override the ClubListView.get_queryset method to apply the appropriate filter.

If there is some really peculiar behaviour that needs to be applied to all the views, it depends on what this behaviour really is about: if it’s related to this specific model, it should probably best be defined in the model itself, or perhaps its manager; and if it’s really something specific to the views, you should write and extend a mixin along with the actual view class.

2👍

dispatch is called before post – or, for that matter, get depending on the request. Overriding it should let you set extra information.

The docs lack detail – I didn’t really get it until I read the source. But the source is nicely readable except for being spread across multiple files.

0👍

You could write a get_club method in your parent class. You can then use this in your subclasses, and you don’t have to repeat the logic.

Leave a comment