FBV's vs CBV's
Source: https://wsvincent.com/class-function-based-views/
Last updated
Source: https://wsvincent.com/class-function-based-views/
Last updated
Within Django a views.py
file adds logic to HTTP requests and responses. If we attempt to visualize how a Django webpage is displayed the process goes something like this:
user enters in a URL like example.com
a urls.py
file identifies the proper URL route
the views.py
file associated with that URL route handles the HTTP request, specifies the proper template, database model (if needed), and logic necessary, and then sends back an HTTP response to the user
This process happens over and over again for each webpage within a Django site.
Historically Django used only function-based views (FBV). These take a standard Python function form of accepting a request
object as an argument and returning a response
object.
Here is an example of a function that returns a simple template. For simplicity, no database models are included here.
Notice that the view accepts a single request
object as the argument and uses the built-in shortcut to return a response. In this case, it displays the template index.html
within the helloworld
app.
Upside: there is no hidden behavior; you know exactly what you’re getting. Decorators can be added, yes, but largely what you see is what you get.
Downside: length and repetition.
What’s the cost? You need to understand the underlying inheritance structure well before you start making changes.
Personally I always start with a GCBV if possible, drop down to a CBV if needed, and if I really must get granular with behavior I’ll use a FBV on occasion.
Starting with class-based views were added and by leveraging inheritance, views code became much more concise. Also customizing an existing CBV is straight-forward; only the parts that have changed need to be updated. Goodbye repetition. And goodbye long, hard-to-read views.
Django took this a step further with Generic Class-based Views (GCBVs) which handle common use cases such as , displaying content in , or as an .
GCBVs are wonderfully concise and powerful. However they can be hard to customize since that requires diving into their internals and really understanding the underlying methods and inheritance structure. is a wonderful resource for unpacking views in this way.
It’s worth noting that the uses CBVs and via more and more behavior that in the past required a FBV is becoming available within a CBV context.