Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django class-based views function execution order

I'm converting some django views to be class based, and so far loving the flexibility.

Most of my views subclass from a parent view ClubView. Each subclassed view that needs to handle a post() method override needs to have access to the corresponding club value.

This value is in the URL, so the request variable has it. However, is there a way for me to grab this value, and fetch the corresponding club object outside of the post() method? like a pre-post() method or something. Mainly because I don't want to copy/paste club = Club.objects.get(...

A more general question -- in what order do all the methods execute in? Django's documentation on this seems lacking.

like image 773
Mikhail Avatar asked Jul 21 '13 02:07

Mikhail


People also ask

Which is better class-based view or function based view Django?

Class based views are excellent if you want to implement a fully functional CRUD operations in your Django application, and the same will take little time & effort to implement using function based views.

How do Django class-based views work?

A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.

What is the difference between function based and class-based views?

Class-based views are the alternatives of function-based views. It is implemented in the projects as Python objects instead of functions. Class-based views don't replace function-based views, but they do have certain advantages over function-based views.

What is Fbv and CBV?

Django has two types of views; function-based views (FBVs), and class-based views (CBVs). Django originally started out with only FBVs, but then added CBVs as a way to templatize functionality so that you didn't have to write boilerplate (i.e. the same code) code over and over again.


2 Answers

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()
like image 146
Pretzel Avatar answered Sep 17 '22 20:09

Pretzel


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.

like image 41
Peter DeGlopper Avatar answered Sep 21 '22 20:09

Peter DeGlopper