98π
The single most significant advantage is inheritance. On a large project itβs likely that you will have lots of similar views. Rather than write the same code again and again, you can simply have your views inherit from a base view.
Also django ships with a collection of generic view classes that can be used to do some of the most common tasks. For example the DetailView class is used to pass a single object from one of your models, render it with a template and return the http response. You can plug it straight into your url conf..
url(r'^author/(?P<pk>\d+)/$', DetailView.as_view(model=Author)),
Or you could extend it with custom functionality
class SpecialDetailView(DetailView):
model = Author
def get_context_data(self, *args, **kwargs):
context = super(SpecialDetailView, self).get_context_data(*args, **kwargs)
context['books'] = Book.objects.filter(popular=True)
return context
Now your template will be passed a collection of book objects for rendering.
A nice place to start with this is having a good read of the docs (Django 4.0+).
Update
ccbv.co.uk has comprehensive and easy to use information about the class based views you already have available to you.
29π
When I started with DJango I never used CBVs because of their learning curve and a bit complex structure. Fast forward over two years, I use FBVs only at few places. Where I am sure the code will be really simple and is going to stay simple.
Major benefit of CBVs and Multiple Inheritance that comes along with them is that I can completely avoid writing signals, helper methods and copy paste code. Especially in the cases where the app does much more than basic CRUD operations. Views with multiple inheritance are multiple times easier to debug than a code with signals and helper methods, especially if it is an unknown code base.
Apart from Multiple inheritance, CBVs provide different methods to do dispatching, retrieving templates, handling different request types, passing template context variables, validating forms, and much more out of the box. These make code modular and hence maintainable.
- [Django]-Django β How to rename a model field using South?
- [Django]-Django MultiValueDictKeyError error, how do I deal with it
- [Django]-Django TemplateSyntaxError β 'staticfiles' is not a registered tag library
21π
Some views are best implemented as CBVs, and others are best implemented as FBVs.
If you arenβt sure which method to choose, see the following chart:
- [Django]-TypeError: data.forEach is not a function
- [Django]-How to add multiple objects to ManyToMany relationship at once in Django ?
- [Django]-Programmatically saving image to Django ImageField
19π
SOME WORDS FROM TWO SCOOPS
Tip Alternative Apporach β Staying With FBVs
Some developer prefer to err on the side of using FBVs for most views and CBVs only for views that need to be subclassed. That strategy is fine as well.
- [Django]-Passing STATIC_URL to file javascript with django
- [Django]-Best practices for getting the most testing coverage with Django/Python?
- [Django]-How to reset db in Django? I get a command 'reset' not found error
11π
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.
I will recommend you to use function based views when you are not going to implement any CRUD on your site/application means your intension is to simply render the template.
I had created a simple CRUD based application using class based views which is live. Visit http://filtron.pythonanywhere.com/view/ (will/wonβt be working now) and enjoy. Then you will know the importance of it.
- [Django]-How to add superuser in Django from fixture
- [Django]-Django: Adding "NULLS LAST" to query
- [Django]-Django datefield filter by weekday/weekend
0π
I have been using FBVs in most of the cases where I do not see a real opportunity of extending views. As documented in the docs, I consider going for CBVs if the following two characteristics suit my use-case.
- Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
- Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.
- [Django]-Programmatically saving image to Django ImageField
- [Django]-Django staticfiles not found on Heroku (with whitenoise)
- [Django]-What's the difference between CharField and TextField in Django?
-1π
Function-Based Views(FBVs) are:
- Easy to use but the
- Code is not reusable by inheritance.
- Recommended to use
Class-Based Views(CBVs) are:
- Too much learning curve because itβs really complicated
- Code is reusable by inheritance.
- Not recommended to use (FBVs are much beter)
- [Django]-Django: reverse accessors for foreign keys clashing
- [Django]-Django Background Task
- [Django]-TemplateDoesNotExist β Django Error