What is Class View in Django?
The class view is used to create view methods using class and object patterns, it provides better usability and oops features implementation in the Django Project.
Django provides two different types of view approach
1) Method View:- We will create a separate method under file to implement the functionality.
def Methodname(request):
statements
2) Class View:- We will create a separate class to define the URL method using a separate block for the getting and post method.
class Classname(View):
def get(self,request):
statements
def post(self,request):
statermets
Class-based view URL pattern will be different as compared to method view?
urlpatterns = [
path('urlpath/', Classame.as_view()),
]
as_view() will be called Class view get method
Django provides a separate module to implement Class View
Step1st:-
go into views.py and create a class using the following module:
from django.views import View
class GreetingView(View):
greeting = "Good Day"
def get(self, request):
return HttpResponse(self.greeting)
Step2nd:-
Implement Urls to define a class view:-
from frontdesk.views import GreetingView
urlpatterns = [
path('grt/', GreetingView.as_view()),
]
Render View in Django using Class View:-
class Hello(View):
s = "frontdesk/index.html"
def get(self,request):
return render(request,self.s)
Post a Comment
POST Answer of Questions and ASK to Doubt