Updating Views Permissions in Django REST Framework

Lesson Introduction

Hello! In this lesson, we are exploring an integral part of building a secure API using the Django REST Framework (DRF): controlling access to your API by updating view permissions. Think of permissions like a classified vault; you wouldn’t want everyone to have access, right? Similarly, for your web application, you want to control who can view, modify, or delete specific data.

Our goal is to understand and implement permission_classes and authentication_classes for API views, which helps us define who can perform certain actions. This knowledge is critical to ensuring your application remains secure while providing the right level of access to your users. Let's unlock the secrets to API view security together!

Setup

Before we start, one important note. Now, our Todo model has a user as its field. However, we won't usually pass the user data when creating a Todo instance. Instead, we will simply fetch the current authenticated user and set them as an owner. This means that we don't need user to be present in the serializer fields. To reflect that, let's update the serializer:

class TodoSerializer(serializers.ModelSerializer):
    group = GroupSerializer(required=False)
    tags = TagSerializer(many=True, required=False)

    class Meta:
        model = Todo
        exclude = ['user']  # Do not include user in the fields

This way, we include all the fields, except 'user'.

Understanding Permission and Authentication Classes

To get started, let’s talk about permission_classes and authentication_classes. Think of permission_classes as the gatekeeper of your application — how friendly or restrictive the gatekeeper is determines who can pass through the gate.

In DRF, permission_classes define rules about whether a specific user can perform a given action on your API endpoint. In TodoListCreate, we use IsAuthenticatedOrReadOnly. This allows any user to fetch data (GET requests) but restricts modifying actions (POST requests) to authenticated users. authentication_classes act as proof of identity. We use TokenAuthentication, meaning users need to supply a valid token to prove identity.

Code Snippet Walkthrough: TodoListCreate

Here's how this setup works in practice with TodoListCreate:

from rest_framework import generics
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.authentication import TokenAuthentication
from .models import Todo
from .serializers import TodoSerializer

class TodoListCreate(generics.ListCreateAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    authentication_classes = [TokenAuthentication]

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

Our TodoListCreate view allows any visitor to browse through the list of to-dos. However, only a logged-in (authenticated) user can create new to-dos. The view leverages permissions and authentication to secure the data.

The perform_create method ensures that the user who creates a new to-do is set as its owner. When a POST request is made, this method assigns user=self.request.user to the new Todo instance via serializer.save(), automatically linking the to-do to the authenticated user, thereby ensuring secure ownership.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal