How to handle MethodNotallowed exception in django rest framework by creating seperate file for exceptions

512 Views Asked by At

In my Django RestApi project I want to apply Exceptions errors. I create a separate file (common.py) for all my exceptions file is located out side the project where our manage.py file located. this is in my file:

HTTP_STRING = {
'get': 'get',
'post': 'post',
'put': 'put',
'patch': 'patch',
'delete': 'delete',

}

Also I set it in settings.py:

  REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',

Now In my view I create a modelviewset. In modelviewset we get all built in functions to perform oprations like (put, patch, delete, create, update) but in this view I don't need put, patch, and delete. So I want to block this and want to give exception on it I tried this :

from rest_framework import viewsets
from common_strings import HTTP_STRING
class DemoModelViewSet(viewsets.ModelViewSet):
      queryset = DemoModel.objects.all()
      serializer_class = DemoModelSerializer
      def update(self, request, pk=None):
          raise MethodNotAllowed(method=HTTP_STRING['put'])

      def partial_update(self, request, pk=None):
          raise MethodNotAllowed(method=HTTP_STRING['patch'])

      def destroy(self, request, pk=None):
          raise MethodNotAllowed(method=HTTP_STRING['delete'])

But giving error on MethodNotAllowed is not defined. Why this is happenning?

1

There are 1 best solutions below

0
On

I was having a similar issue.

According to the exceptions page on Django REST framework website, I think you have to import the exceptions module.

Importing the exceptions module would look something like:

from rest_framework import exceptions

and then raising the exceptions would look like,

exceptions.MethodNotAllowed(method=HTTP_STRING['put'])
exceptions.MethodNotAllowed(method=HTTP_STRING['delete'])
exceptions.MethodNotAllowed(method=HTTP_STRING['patch'])