How to convert your Function Based View into a Class Based View in Django?

How to convert your Function Based View into a Class Based View in Django?

I will never cheat on you, Django.

Note: If you are looking for a Full Stack Developer (Django+React), then connect with me on LinkedIn or contact me through my portfolio.

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 GET and POST requests.

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:

  • RedirectView

  • TemplateView

  • View

Authentication Views:

  • LoginView

  • LogoutView

  • PasswordChangeDoneView

  • PasswordChangeView

  • PasswordResetCompleteView

  • PasswordResetConfirmView

  • PasswordResetDoneView

  • PasswordResetView

Generic CRUD Views:

  • CreateView

  • DeleteView

  • DeleteViewCustomDeleteWarning

  • FormView

  • UpdateView

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!