[Fixed]-Django: Generic views based 'as_view()' method

38👍

In class-based views, you have to call as_view() function so as to return a callable view that takes a request and returns a response. It’s the main entry-point in request-response cycle in case of generic views.

as_view is the function(class method) which will connect my MyView class with it’s url.

From django docs:

classmethod as_view(**initkwargs)
Returns a callable view that takes a request and returns a response:

You just can’t use class-based views like you could in normal function-based views.

BlogIndex(request) # can't do this in case of CBVs

The above code is not valid if you want the CBVs to function properly. For that, you need to provide a view which is callable and then pass request to it. For example:

response = MyView.as_view()(request)  # valid way

By calling the as_view() function on my view class MyView will give me a view which I will call with request parameter to initiate the request-response cycle.

In your case:

my_callable_view = BlogIndex.as_view() # returns a callable view
<function blog.views.BlogIndex>

Now, call this function and pass the request.

 response = my_callable_view(request) # generate proper response

3👍

view function have different format than before because :

  1. This view will actually be implemented as a class
  2. We will be inheriting from an existing generic view function that already does most of what we want this view function to do, rather
    than writing our own from scratch.
  3. Class method as_view()- this does all the work of creating an instance of the class, and making sure that the right handler methods
    are called for incoming HTTP requests.

ref : https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views

👤Deepak

0👍

Maybe I can try to write the as_view with pseudo-code:

class ViewClass():
      #other stuff
      def as_view(self):
           return self.render(*args)

It return the render function inside the CBV.
So it actually is the same as path(‘some_path’,views.some_view_function,name=’some_name’)
Of course, there there is actually much more things going on than only render function, for example to verify and save the content inside post queryDict, actually you need def post(): to handle the post, in function you just if request.method == 'POST' they are actually mutual.
To be specific, as_view() just generate a overall function, including if request.method =='POST': #some code Maybe the actual code doesn’t work like that, but you could understand it this way if you are not prepared to contribute to django source code yourself.

Leave a comment