What is Class View in Django?

0

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)




Now I am explaining another example of ClassView using GET and POST Method both:-

1)  Create urls.py

from appname.views import Classname

path('path',Classname.as_view()),


2) 
from django.shortcuts import render
from django.views import View

class Classname(View):
    def post(self,request):
       logic of post
    

    def get(self,request):
         logic of get





Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)