In this lesson we want to talk about Class Based vs Function Based Views in Django, In Django, there are two main approaches to handling HTTP requests and returning HTTP responses: class based views (CBVs) and function based views (FBVs). both approaches have their pros and cons, and the choice between the two often comes down to personal preference and the specific requirements of the project.
Function based views are just that functions that handle HTTP requests and return HTTP responses. they are simple and straightforward, and are good choice for small and simple views.
Class based views on the other hand are classes that inherit from Django’s built in View class. they provide more organized and reusable way of handling HTTP requests and returning HTTP responses. CBVs are particularly useful when you need to handle multiple HTTP methods (e.g. GET, POST, etc.) in the same view, or when you need to perform certain actions before or after processing request.
In summary, both FBVs and CBVs have their uses, and the choice between the two often comes down to the complexity of the view and the specific requirements of the project. if you are starting new project or adding new view, consider using CBV. they tend to be more flexible and provide a cleaner separation of concerns. if you are working with an existing project and just need to add simple view, FBV might be good choice.
This is an example of function based view in Django:
1 2 3 4 |
from django.shortcuts import render def index(request): return render(request, 'index.html') |
And this is an example of a class based view:
1 2 3 4 |
from django.views.generic import TemplateView class IndexView(TemplateView): template_name = 'index.html' |
In the function based view the index function takes in request object and returns render function that will render the index.html template.
In the class based view IndexView class inherits from TemplateView and sets the template_name attribute to index.html. TemplateView class is built in Django class that implements common behavior for rendering templates. IndexView class will automatically render index.html template whenever it receives an HTTP request.