Django:基于通用视图的“ as_view()”方法 [英] Django: Generic views based 'as_view()' method
问题描述
我正在开发一个应用程序,其中创建了一个通用的 ListView
。现在,在我的 urls.py
中定义该视图时,我从文档中读取了我需要使用 as_view()
方法如下:
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?
推荐答案
在基于类的视图中,您必须调用 as_view()
函数以便返回一个可调用视图,该视图需要一个请求
,并返回一个响应。
它是通用视图下请求-响应周期中的主要入口点。
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
是函数(类方法),它将把我的 MyView
类与其URL连接起来。
as_view
is the function(class method) which will connect my MyView
class with its url.
来自 django文档:
classmethod as_view(** initkwargs)
返回一个可调用的视图,该视图接受一个请求并返回一个响应:
classmethod as_view(**initkwargs)
Returns a callable view that takes a request and returns a response:
您只是不能使用class基于视图的视图,就像在普通基于函数的视图中一样。
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
如果您希望CBV正常运行,则以上代码无效。为此,您需要提供一个可调用的视图,然后将请求传递给它。例如:
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
通过在视图类 MyView上调用
给我一个视图,我将使用 as_view()
函数 request
参数调用该视图以启动请求-响应周期。
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.
在您的情况下:
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
这篇关于Django:基于通用视图的“ as_view()”方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!