0
0
Djangoframework~5 mins

DRF permissions in Django

Choose your learning style9 modes available
Introduction

Permissions in Django REST Framework (DRF) control who can access your API. They help keep your data safe by allowing only the right users to do certain actions.

When you want to let only logged-in users see or change data.
When you want to allow only the owner of an object to edit it.
When you want to make some API endpoints public but others private.
When you want to restrict access based on user roles like admin or staff.
Syntax
Django
from rest_framework.permissions import BasePermission

class CustomPermission(BasePermission):
    def has_permission(self, request, view):
        # Return True if user has permission
        return True  # or False

    def has_object_permission(self, request, view, obj):
        # Return True if user has permission for this object
        return True  # or False

has_permission checks general access to the view.

has_object_permission checks access to a specific object.

Examples
This lets only users who are logged in access the API.
Django
from rest_framework.permissions import IsAuthenticated

# Use built-in permission to allow only logged-in users
permission_classes = [IsAuthenticated]
This custom permission allows only the owner of an object to access it.
Django
from rest_framework.permissions import BasePermission

class IsOwner(BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user
This makes the API open to everyone, no login needed.
Django
from rest_framework.permissions import AllowAny

# Allow anyone to access the API
permission_classes = [AllowAny]
Sample Program

This API view only lets logged-in users access it. When accessed, it greets the user by their username.

Django
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

class HelloView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({"message": f"Hello, {request.user.username}!"})
OutputSuccess
Important Notes

Always set permission_classes on your views to protect your API.

Use built-in permissions like IsAuthenticated before writing custom ones.

Test your permissions by trying to access the API as different users.

Summary

DRF permissions control who can use your API.

Use built-in permissions for common cases like logged-in users.

Create custom permissions for special rules like ownership.