基于 Django 类的视图 __init__() 缺少 1 个必需的位置参数

Django Classed based view __init__() missing 1 required positional argument

我正在尝试在 Django 中使用基于 class 的视图!

我的urls.py:

path('pie-chart/', views.pie_chart, name='pie_chart.html'),

我的view.py

class pie_chart(View):
    def __init__(self, labels, data):
        self.labels = labels
        self.data = data


    def active_sessions(self, request):
        self.labels = []
        self.data = []
        queryset = Employees.objects.values('department__name').annotate(total_session=Count('employeeconnection__employeesession'))
        for item in queryset: 
            self.labels.append(item['department__name'])
            self.data.append(item['total_session'])

        return render(request, 'pie_chart.html', {
            'labels': self.labels,
            'data': self.data,
        })

我收到此错误:

__init__() missing 1 required positional argument: 'data'

使用基于 class 的视图时,在 url 中注册此视图时必须调用 as_view class 方法,而不是简单地将其传递给 url:

path('pie-chart/', views.pie_chart.as_view(), name='pie_chart.html'),

您需要正确使用 View 方法 - 为 GET 请求设置处理程序方法:

class PieChart(View):

    def get(self, request, *args, **kwargs):
        labels = []
        data = []
        queryset = employees.objects.values('department__name').annotate(total_session=Count('employeeconnection__employeesession'))
        for item in queryset: 
            labels.append(item['department__name'])
            data.append(item['total_session'])
        return render(request, 'pie_chart.html', {
                'labels': labels,
                'data': data,
            })

然后在urls.py中调用as_view():

path('pie-chart/', views.PieChart.as_view(), name='pie_chart.html'),

并且您不需要重写视图 __init__ 方法来接收来自请求的参数。