python - 基于 django 类的 View 不接受 view_args 和 view kwargs

标签 python django django-views django-middleware

我使用的是 django 1.8。我在我的一个 View 中使用 django.views.generic.View 类。

class CommonView(View):
    func_name = 'view_func'
    http_method_names = ["get", "post"]
    def get(self, request, *args, **kwargs):
        return render(request, 'template.html', {})

在 urls.py 中我添加了

url(r'^common/$',CommonView),

我编写了一个中间件,我正在其中进行一些 View 响应和重写的 process_view 方法

class CommonMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        response = view_func(request, *view_args, **view_kwargs)
        """ Do something"""
        return response

但是在这一行response = view_func(request, *view_args, **view_kwargs)我收到错误

__init__() takes exactly 1 argument (3 given)
Request Method: POST
Request URL:    http://127.0.0.1:8000/common/
Django Version: 1.8
Exception Type: TypeError
Exception Value:    
__init__() takes exactly 1 argument (3 given)

在此之前我必须检查 View 函数的func_name。但是在中间件类中,当我尝试从 view_func 获取 func_name 属性时,我收到了 AttributeError ,该 CommonView 没有属性 func_name 而我是从所有基于函数的 View 中获取它的。

最佳答案

错误在这一行

url(r'^common/$',CommonView),

你必须使用

url(r'^common/$',CommonView.as_view()),

在从 url 调用基于类的 View 时,您忘记添加 as_view()

关于python - 基于 django 类的 View 不接受 view_args 和 view kwargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44700375/

相关文章:

python - 等待 Python 中 Selenium 的 XHR 请求和/或控制台消息

python - 从 python 读取 BerkleyDB 文件 : `\x01\x0b\x88\x0c\x01` ?

django - 内容类型和表示

python - Apache mod_wsgi 32 位/64 位 Python 兼容性

python - 更新用户个人资料时 upload_to 不起作用?

python - Django 使用来自表单字段的变量运行 python 脚本

python - Django 别名将错误的 url 重定向到正确的 url

python - 将日期巧妙地添加到悬停模板中

带有选项字段的 Django value_list

django - APIView和Model ViewSet在使用或继承上有什么区别