how to fix Django: @action Method \”GET\” not allowed with code example?

In Django REST framework, the @action decorator is used to define custom actions that can be performed on a ViewSet. By default, DRF maps these actions to HTTP methods based on their names. If you’re encountering an error saying “Method ‘GET’ not allowed,” it typically means that you’re trying to access an action with an HTTP method that’s not allowed for that action.

Here’s how you can fix this issue:

Example Scenario: Let’s assume you have a ViewSet called ProductViewSet and you’ve defined a custom action called custom_action using the @action decorator.

Step 1: Check the Allowed HTTP Methods: By default, DRF maps the names of the custom actions to the following HTTP methods:

  • create: POST
  • update: PUT
  • partial_update: PATCH
  • destroy: DELETE

If you’re trying to access your custom action using an HTTP method that doesn’t match the default mapping, you’ll get a “Method not allowed” error.

Step 2: Specify Allowed Methods Using ‘methods’ Parameter: You can explicitly specify the allowed HTTP methods for your custom action using the methods parameter of the @action decorator. This allows you to control which HTTP methods are allowed for the custom action.

from rest_framework.decorators import action

class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer

# Example custom action
@action(detail=True, methods=['GET', 'POST']) # Allow both GET and POST methods
def custom_action(self, request, pk=None):
# Your custom action logic here
return Response({'message': 'Custom action performed successfully'})

In this example, the custom_action method is now allowed to be accessed using both the GET and POST HTTP methods.

Step 3: Verify the URL Pattern: Ensure that the URL pattern for your custom action is correctly configured in your file.

router = DefaultRouter()
router.register(r'products', ProductViewSet)

urlpatterns = [
# Your other URL patterns
path('', include(router.urls)),

Make sure that the URL pattern for your custom action matches the action name, and the HTTP methods specified in the methods parameter of the @action decorator are allowed.

By specifying the allowed HTTP methods explicitly using the methods parameter of the @action decorator, you can ensure that you don’t encounter the “Method not allowed” error when accessing your custom actions in Django REST framework.