ninesalt
ninesalt

Reputation: 4354

How to have different permission classes for methods in DRF

I have a view similar to this:

from django.http import HttpResponse
from rest_framework import generics

class MyView(generics.ListCreateAPIView):

    def get_queryset(self):
        # <view logic>
        return HttpResponse('result')

    def post(self, request):
        # <view logic x2>
        return HttpResponse('message_post_template')

And I would like the GET request to have the permission class of IsAuthenticated and the POST request should have a permission class of HasAPIKey from Django REST Framework API Key. How can I do this?

I tried doing permission_classes = [IsAuthenticated | HasAPIKey] but that would be too lenient because it would allow the functions to work if the other permission other than the one required is available.

Upvotes: 2

Views: 1285

Answers (1)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

from django.http import HttpResponse
from rest_framework import generics

class MyView(generics.ListCreateAPIView):

    def get_permissions(self):
        method = self.request.method
        if method == 'POST':
           return [HasAPIKey()]
        else:
           return [IsAuthenticated()]

    def get_queryset(self):
        # <view logic>
        return HttpResponse('result')

    def post(self, request):
        # <view logic x2>
        return HttpResponse('message_post_template')

Reference:
https://github.com/encode/django-rest-framework/blob/dff9759555eefef67c552f175d04bb7d8381e919/rest_framework/views.py#L274

Upvotes: 3

Related Questions