【问题标题】:django-rest-framework "AttributeError: 'function' object has no attribute 'get_extra_actions' "django-rest-framework "AttributeError: 'function' object has no attribute 'get_extra_actions' "
【发布时间】:2021-06-14 12:23:42
【问题描述】:

django==3.2.4 djangorestframework==3.12.4

blog/serializer.py

from rest_framework import serializers
from .models import Blog

class BlogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blog
        fields = '__all__'

blog/views.py

from rest_framework import generics
from .models import Blog
from .serializers import BlogSerializer

class BlogListCreateView(generics.ListCreateAPIView):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

class BlogRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

博客/urls.py

router = DefaultRouter()
router.register(r'blogs', BlogListCreateView.as_view(), basename="blogs")
router.register(r'action/<int:pk>', BlogRetrieveUpdateDestroyView.as_view(), basename="action")

urlpatterns = [
    path('', include(router.urls)),
]

当我使用路由器时,它显示 AttributeError: 'function' object has no attribute 'get_extra_actions' 但是当我使用正常的 django urls 路径时,它运行成功

博客/urls.py

urlpatterns = [
    path('blog/', BlogListCreateView.as_view(), name="blog"),
    path('blog/<int:pk>', BlogRetrieveUpdateDestroyView.as_view(), name="action"),
]

【问题讨论】:

  • 路由器用于viewsets而不是views...

标签: python django django-rest-framework


【解决方案1】:

来自文档:

因为我们使用的是 ViewSet 类而不是 View 类,所以我们 其实不需要自己设计URL conf。公约 用于将资源连接到视图中,并且可以处理 url 自动,使用路由器类。

所以你不需要路径是'action/&lt;int:pk&gt;''action' 就足够了。

【讨论】:

    【解决方案2】:

    Routers 用于Viewsets,而不用于来自 Django 的 generics 视图。例如:

    from rest_framework import routers
    
    router = routers.SimpleRouter()
    router.register(r'users', UserViewSet)
    router.register(r'accounts', AccountViewSet)
    urlpatterns = router.urls
    

    Here's 如何使用generics

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 2019-02-28
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 2020-04-26
      相关资源
      最近更新 更多