【问题标题】:Django - missing 1 required positional argument: 'request'Django - 缺少 1 个必需的位置参数:“请求”
【发布时间】:2018-01-24 23:32:19
【问题描述】:

我收到了错误

get_indiceComercioVarejista() 缺少 1 个必需的位置参数: '请求'

当尝试访问 get_indiceComercioVarejista 方法时。我不知道它有什么问题。

观看次数:

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
import requests
import pandas as pd

from rest_framework.views import APIView
from rest_framework.response import Response

class ChartData(APIView):

    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):

         data = {
            'customer' : 10,
            'sales': 100
        }

        return Response(data)

    def get_indiceComercioVarejista(self, request, format=None):
        data = {
            'customer' : 10,
            'sales': 100
        }
        return Response(data)

网址:

from django.conf.urls import url
from . import views
from django.contrib.auth.views import login

urlpatterns = [
    url(r'^$', views.home),
    url(r'^login/$', login, {'template_name': 'Oraculum_Data/login.html'}),
    url(r'^cancerColo/$', views.cancerColo),
    url(r'^educacao/$', views.educacao),
    url(r'^comercio/$', views.comercio),
    url(r'^saude/$', views.saude),
    url(r'^api/chart/data/$', views.ChartData.as_view()),
    url(r'^api/chart/indiceVolumeReceitaComercioVarejista/$', views.ChartData.get_indiceComercioVarejista)
]

有人可以帮帮我吗?

【问题讨论】:

  • 您希望.get 这样做并在您的网址中使用views.ChartData.as_view()...(或者如果您有超过一个取决于任何标准...)

标签: python django web django-rest-framework


【解决方案1】:

request 作为第一个参数传递。你的第一个参数是self

这就是为什么从ChartData 类中提取get_indiceComercioVarejista 是个好主意:

def get_indiceComercioVarejista(request, format=None):
    data = {
        'customer' : 10,
        'sales': 100
    }
    return Response(data)

【讨论】:

  • 仍然无法正常工作。 get 方法将 self 作为第一个参数传递,它工作正常。
  • 您是否从类中提取了get_indiceComercioVarejista 方法? get 方法将起作用,因为您通过 as_view() 使用它,
【解决方案2】:

我认为最好的方法是将get_indiceComercioVarejista 移出APIView,因为APIView 只是调度到常规http 方法:get post put patch delete

例如:

view.py

def get_indiceComercioVarejista(request, format=None):
    data = {
        'customer' : 10,
        'sales': 100
    }
    return Response(data)

urls.py

url(r'^api/chart/indiceVolumeReceitaComercioVarejista/$', views.get_indiceComercioVarejista)

另一个解决方案是使用ViewSet,这是在使用 DRF 时推荐的。

【讨论】:

  • 没用。错误:TypeError:as_view() 接受 1 个位置参数,但给出了 2 个
猜你喜欢
  • 2018-11-18
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 2021-08-12
  • 2020-05-07
  • 2018-12-12
相关资源
最近更新 更多