I'm currently struggeling with some django rest framework issues. I want to define a delete request for my APIView.
This is my view.py:
class Employee(APIView):
permission_classes = (AllowAny, )
serializer_class = EmployeeSerializer
def get(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
serializer = EmployeeSerializer(employee, many=False)
return Response(serializer.data)
def delete(self, request, pk, format=None):
employee = EmployeeModel.objects.get(pk=pk)
employee.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
And this is my urls.py:
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
path('api/auth/', include('rest_framework.urls')),
path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
path('api/', include(router.urls)),
path('api/v1/employeelist/', views.EmployeeList.as_view()),
path('api/v1/employee/<pk>', views.Employee.as_view())
]
Serializer:
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = '__all__'
depth = 1
The get method works fine when I call /api/v1/employee/4 for instance. The UI of the API shows me the allowed methods: GET, DELETE, HEAD, OPTIONS but when I send a delete request I always get the error 403 forbidden.
Does anybody know why?
It doesn't matter what the serializer class is unless you use get_serializer() and even then it's working fine with your get request. I believe your issue for the delete is that you may be using SessionAuthentication or BasicAuthentication (the defaults for DRF). Try making your view csrf_exempt.
Set authentication_classes = []
for your APIView. DRF has SessionAuthentication and BasicAuthentication by default, and you need to disable it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.