I have to allow delete and update requests from front for my objects of some model. I wish to delete the instance and appropriate row in DB.
I tried to use info from DRF tutorials (https://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/) , some other examples. I understand if I using ViewSet I have to allow some actions and using rows. I use decorator like in DRF tutorial.
There is my view.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)
my actions in app 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])
so a part of my project 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)),
]
So result: TypeError: The `actions` argument must be provided when calling `.as_view()` on a ViewSet. For example `.as_view({'get': 'list'})
If I set some action like in example was thrown by terminal: router.register(r'cutarea', DualFcaPlanUseViewSet.as_view('destroy': 'delete'), base_name='cutareadel')
I face syntax error...
I want to understand how viewset works with routers, and which good way to allow extra HTTP methods (delete, update etc.)
Turns out, if I use this:
router.register(r'cutarea', DualFcaPlanUseViewSet, base_name='cutareadel')
The error is solved. But the DELETE method is not allowed. What is wrong?
router.register(r'cutarea', DualFcaPlanUseViewSet, base_name='cutareadel')
api/cutarea/ allows only: GET, POST, HEAD, OPTIONS . No DELETE. Request from frontside doesn't work too. – Bestialize