【问题标题】:django classbased view not accepting view_args and view_kwargsdjango 基于类的视图不接受视图参数和视图 kwargs
【发布时间】:2026-01-28 02:50:01
【问题描述】:

我正在使用 django 1.8。我在我的一个视图中使用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),

我已经编写了一个中间件,我在其中对视图响应和覆盖 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)

在此之前,我必须检查视图函数的func_name。但是在中间件类中,当我试图从view_func 获取func_name 属性时,我得到了AttributeErrorCommonView has no attribute func_name,而我是从所有基于函数的视图中获取它的。

【问题讨论】:

    标签: python django django-views django-middleware


    【解决方案1】:

    错误在这一行

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

    你必须使用

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

    您在从 url 调用时忘记在基于类的视图中添加 as_view()

    【讨论】:

    • 啊,这是一个愚蠢的错误。花了几个小时找到错误。