As the name suggests, Django views can also be written in Class based style. The major advantage of using Class based views in Django is
- Code reusability and Clean Code
But, when creating a complex Class with lots of inheritance or mixins can make the situation hard to debug.
To create a Class() based view we subclass django.views.View
from django.views import View
class DashboardView(View):
def get(self, request):
# GET method
pass
def post(self, request):
# POST method
pass
Converting examples from our function() based views to Class() based views
from django.views import View
from django.http impoty HttpResponse
class DashboardView(View):
def get(self, request):
# process view here
return HttpResponse("Welcome to Dashboard")
#urls.py
urlpatterns = [
path('dashboard/', DashboardView),
]
# this will not work
Since URL configurations expects callable function rather than class, we will use .as_view()
class method of our View because as_view()
returns a function to be used with URLs. This function does series of work for us,
- calls
setup()
method to initialize the attributes - calls
dispatch()
method which determines if request ifGET
orPOST
and send this request to corresponding request method
So on our urls.py
we do the following,
# urls.py
# import your view
urlpatterns = [
path('dashboard/', DashboardView.as_view()),
]
Capturing URL values in Class() based views
If you need to capture values from URL here at Class() based view, its similar to the function() based view, just add the new parameters(arguments) in your respective method.
#urls.py
urlpatterns = [
path('profile/<str:username>/', ProfileView.as_view()),
]
from django.views import View
from django.http impoty HttpResponse
class ProfileView(View):
def get(self, request, username):
# process view here
# get user info from DB using username
return HttpResponse("My Profile")
Note: To make the development fast and easy, Django provides us with generic class based views as well majorly for performing C-R-U-D operations, which we will talk about in another tutorial See Django Docs for Generic class based views