Django的。当我尝试允许DELETE,PUT,ETC时,必须在调用`.as_view()`时提供`actions参数'

时间:2019-05-15 12:13:36

标签: django django-rest-framework django-views http-method

我必须允许从前面删除和更新某些模型对象的请求。我希望删除数据库中的实例和适当的行。

我尝试使用DRF教程(https://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/)中的信息,以及其他一些示例。 我知道如果使用ViewSet,我必须允许一些操作和使用行。我在DRF教程中使用装饰器。

有我的观点。py

class DualFcaPlanUseViewSet(viewsets.ModelViewSet):

    authentication_classes = (CsrfExemptSessionAuthentication,)
    def get_queryset(self): 
        user = self.request.user
        return FcaPlanUse.objects.filter(id_fca__num_of_agree__renters_id__user_key = user)
    def get_serializer_class(self):
        if self.request.method == 'GET':
            return FcaPlanUseSerializer
        if self.request.method == 'POST':
            return FcaPlanUsePOSTSerializer
    @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) 
    def highlight(self, request, *args, **kwargs):
        fcaplanuse = self.get_object()
        return Response(fcaplanuse.highlighted)
    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

我在应用urls.py中的操作

from django.conf.urls import url
from rest_framework import renderers
from . import views
from cutarea.views import DualFcaPlanUseViewSet

fcaplanuse_list = DualFcaPlanUseViewSet.as_view({
    'get': 'list',
    'post': 'create'
})
fcaplanuse_detail = DualFcaPlanUseViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})
fcaplanuse_highlight = DualFcaPlanUseViewSet.as_view({
    'get': 'highlight'
}, renderer_classes=[renderers.StaticHTMLRenderer])

所以我的项目urls.py的一部分

from cutarea.views import *
#...
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'cutarea', DualFcaPlanUseViewSet.as_view(), base_name='cutareadel')
#...

urlpatterns = [
    #...
    url(r'^api/', include(router.urls)),
]

结果是:TypeError: The `actions` argument must be provided when calling `.as_view()` on a ViewSet. For example `.as_view({'get': 'list'})

如果我设置了某些示例,如示例被终端抛出:router.register(r'cutarea', DualFcaPlanUseViewSet.as_view('destroy': 'delete'), base_name='cutareadel'),我将遇到语法错误... 我想了解viewset如何与路由器配合使用,以及一种允许额外HTTP方法(删除,更新等)的好方法。

UPD 如果使用这个

router.register(r'cutarea', DualFcaPlanUseViewSet, base_name='cutareadel')``` The error is solved. But DELETE method not allowed. What is wrong?

1 个答案:

答案 0 :(得分:3)

注册as_view时不使用ViewSet

from cutarea.views import *
#...
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'cutarea', DualFcaPlanUseViewSet, base_name='cutareadel')
#...

urlpatterns = [
    #...
    url(r'^api/', include(router.urls)),
]