Welcome to our deep dive into Permissions in DRF! In this tutorial, we'll explore how to control and secure access to your Django REST API (DRF) by managing user permissions. Let's get started!
In DRF, permissions are used to control and manage the access of authenticated users to your API resources. By setting up appropriate permissions, you can ensure that only authorized users can perform specific actions on your API.
π Note: DRF uses two types of permissions: Authentication and Authorization. Authentication is about verifying the identity of the user, while Authorization deals with controlling access based on the verified identity.
Let's begin with creating a simple view and applying basic permissions to it.
First, we'll create a Post model and its serializer:
from django.db import models
from rest_framework import serializers
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'title', 'content', 'author', 'created_at')Now, let's create a view and set up basic permissions:
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer
from rest_framework.permissions import IsAuthenticated
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]In this example, we've applied the IsAuthenticated permission class, which means that only authenticated users can access the API resources.
Now that we have a basic understanding of permissions, let's delve into more advanced topics.
You can create custom permission classes to enforce more specific access rules. Here's an example of a custom PostOwnerPermission class:
from rest_framework import permissions
class PostOwnerPermission(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
# Read and update actions are allowed only if the user is the post's owner
if request.method in ['GET', 'PATCH'] and obj.author == request.user:
return True
# Delete action is allowed only if the user is an admin or the post's owner
if request.method == 'DELETE' and (request.user.is_superuser or obj.author == request.user):
return True
return FalseAfter creating the custom permission, update the PostViewSet as follows:
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = [PostOwnerPermission, IsAuthenticated]Now, users can only read, update, or delete their own posts, and admins can modify or delete any post.
π― Let's test your understanding!
By understanding and applying permissions in Django REST Framework, you'll be able to secure your API and ensure that only authorized users can access and manipulate your API resources. In this tutorial, we covered the basics of permissions and introduced custom permissions for more specific access control.
π‘ Pro Tip: Always keep your API secure and up-to-date by periodically reviewing and updating your permission settings.
Now that you've learned about permissions in DRF, feel free to explore more advanced topics and apply them to your projects! π Happy coding! π