Django viewset没有属性'get_extra_actions'

juzqafwq  于 2023-08-08  发布在  Go
关注(0)|答案(8)|浏览(133)

我是第一次使用Django,我试图构建一个API,我正在遵循一些教程和示例,它的工作正常,但我现在运行项目在树莓派后安装所有的要求和项目是失败的以下错误:

Performing system checks...

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0xb547adb0>
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
    self.check(display_num_errors=True)
  File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
    for pattern in self.url_patterns:
  File "/home/pi/.local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/pi/.local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 673, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/pi/Projects/openvpn-monitor/openvpnmonitor/urls.py", line 24, in <module>
    url(r'^api/', include('openvpnmonitor.api.urls')),
  File "/home/pi/.local/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 673, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/pi/Projects/openvpn-monitor/openvpnmonitor/api/urls.py", line 16, in <module>
    urlpatterns += router.urls
  File "/home/pi/.local/lib/python3.5/site-packages/rest_framework/routers.py", line 101, in urls
    self._urls = self.get_urls()
  File "/home/pi/.local/lib/python3.5/site-packages/rest_framework/routers.py", line 363, in get_urls
    urls = super(DefaultRouter, self).get_urls()
  File "/home/pi/.local/lib/python3.5/site-packages/rest_framework/routers.py", line 261, in get_urls
    routes = self.get_routes(viewset)
  File "/home/pi/.local/lib/python3.5/site-packages/rest_framework/routers.py", line 176, in get_routes
    extra_actions = viewset.get_extra_actions()
AttributeError: type object 'SessionViewSet' has no attribute 'get_extra_actions'

字符串
我的views.py有以下代码:

from django.shortcuts import render

from rest_framework import viewsets
from .models import Session
from .serializers import SessionSerializer

from rest_framework.views import APIView, Response

class SessionViewSet(APIView):
    queryset = Session.objects.all()
    serializer_class = SessionSerializer

    def get(self, request, format=None):
        return Response("test")


我真的不知道为什么在我的笔记本电脑上工作,但它在我的树莓派上不工作。
有没有人知道为什么会发生这种事?
谢谢你!
编辑:
这里是我的urls.py

from django.conf.urls import url
from rest_framework import routers
from openvpnmonitor.api.views import SessionViewSet

router = routers.DefaultRouter()
router.register(r'sessions', SessionViewSet)

urlpatterns = [
    url(r'sessions', SessionViewSet.as_view()),
    url(r'^docs/', schema_view),
]

urlpatterns += router.urls

bd1hkmkf

bd1hkmkf1#

您称之为视图集,但这并不意味着它就是视图集;您从APIView继承,APIView是一个独立的通用视图,而不是视图集。
视图集需要从viewsets. ViewSet继承。

r7xajy2e

r7xajy2e2#

在Django Rest Framework v3.8之前,您可以直接向路由器注册APIView。我这样做是为了获得一个很好的整理(和版本化)的自动文档API,用于一些 * 非常 * 自定义的API端点。如果再给我一个选择,我可能会用更标准的方式来写整件事,但这并不是每个人的选择。
但是在深入研究了这个错误之后,发现你可以通过给路由器它想要的东西并添加一个虚拟的get_extra_actions类方法来解决这个问题。

class MyAPIView(APIView):

    @classmethod
    def get_extra_actions(cls):
        return []

#...

字符串
我不是说这很好,但现在很有效。
我已经拿回了我的文档,并且我已经设法升级到了DRFv3.8。

7tofc5zh

7tofc5zh3#

用于:

djangorestframework==3.11.0
Django==2.2.9

字符串
您需要将class SessionViewSet(APIView):更改为:

from rest_framework import mixins, viewsets

class SessionViewSet(mixins.ListModelMixin,
                     viewsets.GenericViewSet):


才能让它工作。DRF的内部已经发生了一些变化,其他解决方案将不再削减它。

nzkunb0c

nzkunb0c4#

在views.py中,你的viewset必须继承viewset,并在viewset中使用它。

class SessionViewSet(viewsets.ModelViewSet):
    queryset = Session.objects.all()
    serializer_class = SessionSerializer

    def get(self, request, format=None):
        return Response("test")

字符串

pcww981p

pcww981p5#

请注意视图集类和模型类使用相同的名称。这就是我自己犯错误的原因。看我做的例子

# inside member/views.py
from member.models import Member

# inheriting from model viewset but called Member
class Member(viewsets.ModelViewSet):
    queryset = Member.objects.all()
    ...

# inside urls.py
from member.views import Member

router = routers.DefaultRouter()
router.register(r'member', Member)

字符串
这里的错误是导入了成员模型而不是视图集,但它们的名称相同

7fhtutme

7fhtutme6#

在我的例子中,我所做的是从rest_framework模块中的viewsets.Viewset继承视图,此外,我在注册过程中在router.register()函数中添加了basename = your_name参数。
视图看起来像是:

class SessionViewSet(viewsets.ViewSet):
    queryset = Session.objects.all()
    serializer_class = SessionSerializer

    def get(self, request, format=None):
        return Response("test")

字符串
路由器注册如下所示:

router.register(r'your_app_name', YourModelNameView, basename='your_app_name')

nwo49xxi

nwo49xxi7#

您在类视图中错过了viewsets.GenericViewSet

s2j5cfk0

s2j5cfk08#

基本是我们在views.py创建视图扩展或继承

(CreateModelMixin、RetrieveModelMixin、DestroyModelMixin)和
从rest_framework.generics导入ListCreateAPIView,RetrieveUpdateDestroyAPIView

class CartViewSet(CreateModelMixin,RetrieveModelMixin,DestroyModelMixin ):
       queryset = Cart.objects.prefetch_related("items","items__product").all()
       serializer_class = CartSerializer
       (........)

字符串
但是我们必须从rest_framework.Viewset导入GenericViewSet

class CartViewSet(CreateModelMixin,RetrieveModelMixin,DestroyModelMixin,GenericViewSet ):
     queryset = Cart.objects.prefetch_related("items","items__product").all()
     serializer_class = CartSerializer
     (........)


错误提示不应该发生或消失使用这个只是添加GenericViewSet类在视图类

相关问题