In Django you can use a Function Based View(FBV) or a Class Based View(CBV), both kinds have its own advantages and disadvantages.
But there is no doubt that CBV can make your work a lot easier than FBV by handling some repetitive work for you.
Converting your normal Function Based Views into Class Based Views is pretty simple, let’s see how:
- Suppose our FBV looks something like this:
def my_view(request): if request.method == 'GET': # Your View logic on GET # ... elif request.method == 'POST': # Your View logic on POST # ...
- When you will convert it into a CBV, it will look something like this:
from django.views.generic import View class MyView(View): def get(self, request): # Your View logic on GET # ... def post(self, request): # Your View logic on POST # ...
As you can see that, you just have to use
View class from Django generic views, and just define two methods for
This is the most basic version of CBV give above, but there are some more other CBVs as well for common tasks such as:
Generic Base Views:
Generic CRUD Views:
For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.