Permissions in Django Rest Framework — Part 1

ArRosid
3 min readOct 21, 2019

--

In the previous story, I show you how to create Token based authentication. If you haven’t read it, you can read it first

In this story, We will talk about Permissions in Django Rest Framework. Actually in the two previous story, we already use permission, we use IsAuthenticated permissions.

class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ArticleSerializer
queryset = models.Article.objects.all()
permission_classes = [IsAuthenticated,]

In this story, we will use project from previous story, So I highly recommend you to read it first and also clone the project from my github https://github.com/ArRosid/learn-def

By default, Django Rest Framework has some permission,

  • IsAuthenticated
  • IsAdminUser
  • IsAuthenticatedOrReadOnly

Let’s try that one by one. We already know about IsAuthenticated, this is mean that if we not login, we can’t access the API.

Now Lets try IsAuthenticatedOrReadOnly

from rest_framework.permissions import (IsAuthenticated,
IsAdminUser,
IsAuthenticatedOrReadOnly)
class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ArticleSerializer
queryset = models.Article.objects.all()
permission_classes = [IsAuthenticatedOrReadOnly,]

Let’s test it. We will not login first

We success access the API. but if we try to scroll button, we will not see from to create POST request

Let’s try to access the detail of one article

We also don’t see from to create PUT request and also we don’t see delete button to create DELETE request.

Now let’s login using Token Authentication.

Now we see from to create POST request.

We also has from to create PUT request, also delete button to create DELETE request.

Very cool right? And this is so easy!

I will keep this story simple and short, so you can understand easily. In the next story I will show you about IsAdminUser and how to create custom permission. See you in the next story! Stay tune!

--

--