Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Generic views based 'as_view()' method

I was working on an application wherein I created a generic ListView. Now, while defining that view in my urls.py, I read from the documentation that I need to use the as_view() method as follows:

from django.conf.urls import patterns, include, url
from .views import BlogIndex

urlpatterns = patterns(
    '',
    url(r'^$', BlogIndex.as_view(), name="index"),
)

Now, I didn't really understood what the documentation had to say about this method. Can someone shed some light into this concept?

like image 322
Manas Chaturvedi Avatar asked Jul 18 '15 12:07

Manas Chaturvedi


People also ask

What does As_view () do in Django?

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. Its 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 its url.

What are class-based views and function-based views in Django?

Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: Organization of code related to specific HTTP methods ( GET , POST , etc.)

Should I use class-based views Django?

Generic class-based views are a great choice to perform all these tasks. It speeds up the development process. Django provides a set of views, mixins, and generic class-based views. Taking the advantage of it you can solve the most common tasks in web development.


1 Answers

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. Its 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 its 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
like image 160
Rahul Gupta Avatar answered Oct 04 '22 16:10

Rahul Gupta