Django Rest Framework ReadOnly Permission

Here is how to make our DRF API as read only, so all users (authenticated or unauthenticated) can access the API only read only mode.

# Create permission class.
class ReadOnlyPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.method in permissions.SAFE_METHODS

# Add permission class above to viewset.
class MyAPIViewSet(viewsets.ModelViewSet):
    model = MyAPIModel
    queryset = model.objects.all()
    serializer_class = MyAPISerializer
    permission_classes = (ReadOnlyPermission,)

Simple, eh? 😀

Update, 1 Dec 2015
My friend rezha told me that DRF already had ReadOnlyModelViewSet, so we just need to create sub class of this class.

class MyAPIViewSet(viewsets.ReadOnlyModelViewSet):
    model = MyAPIModel
    queryset = model.objects.all()
    serializer_class = MyAPISerializer

More simple 😀

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s