Disable a method in a ViewSet, django-rest-framework
Instantly disable any method like POST
inside a Django REST Framework ViewSet by overriding and raising a MethodNotAllowed
exception:
For conditional disabling or peculiar methods, adjust with the @action
decorator:
methods=['get']
restricts to only GET requests.
Unleashing http_method_names
Not a fan of overriding each method individually? Use http_method_names and call the shots on your allowed methods:
This little trick even excuses unsupported actions from the Browsable API. Now that's multitasking!
Define your operations with custom mixins
With custom mixins, you can whip up a combination of operations without the extra baggage of ModelViewSet
:
Now, you can balance your CRUD operations like a pro and stay light on your feet!
Custom routers for precise control
Building a custom router helps you mark specific methods as no-go zones in your URL conf, ensuring they don't crash your party unwelcome:
This way, you guarantee that your API schema precisely mirrors the abilities your API is proud of.
Benefit gracefully from DRF 3.14.0
Don't forget to upgrade to DRF 3.14.0 for classy handling of HTTP 405 Method Not Allowed
errors. Say goodbye to any disabled method in your OPTIONS
request, making the powers of your API absolutely clear:
This is as good as a friendly nudge to keep your Django REST Framework upgraded for security patches and an alluring array of new, fancy features.
Was this article helpful?