Django的View视图类self.request和request
View中setup()函数:
def setup(self, request, *args, **kwargs): """Initialize attributes shared by all view methods."""
self.request = request
self.args = args
self.kwargs = kwargs
view视图:
from django.views.generic import Viewclass IndexView(View):
def get(self, request, *args, **kwargs):
return render(self.request, 'index.html')
如果get()函数没有接收request就会报出如下错误:
TypeError: get() takes 1 positional argument but 2 were given~
既然View.setup函数已经将request对象赋值给self.request,get()函数所接收的request和self.request相同,
为什么我还需要在IndexView.get函数中重新接收一遍呢?
回答:
为了能够回答你的问题,特地去GitHub看了源码: https://github.com/django/django/blob/stable/1.3.x/django/views/generic/base.py
时间序列:
- 1.3版本引入了
base.py
即class View
.
@classonlymethoddef as_view(cls, **initkwargs):
# ...
def view(request, *args, **kwargs):
self = cls(**initkwargs)
return self.dispatch(request, *args, **kwargs)
# take name and docstring from class
update_wrapper(view, cls, updated=())
- 2.2版本出现了
View.setup()
查看代码:Fixed #29750 -- Added View.setup() hook for class-based views.
具体原因可查看:https://github.com/django/django/pull/10427
看到这里,应该能知道原因了吧。
以上是 Django的View视图类self.request和request 的全部内容, 来源链接: utcz.com/a/159550.html