0
0
Djangoframework~5 mins

Custom permissions in Django

Choose your learning style9 modes available
Introduction

Custom permissions let you control who can do what in your Django app. They help keep your app safe and organized.

You want only certain users to edit or delete specific data.
You need to restrict access to parts of your app based on user roles.
You want to add special rules beyond Django's default permissions.
You want to check permissions in your views or APIs before allowing actions.
Syntax
Django
from rest_framework.permissions import BasePermission

class MyCustomPermission(BasePermission):
    def has_permission(self, request, view):
        # return True if user has permission
        return condition

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

Custom permissions are classes that inherit from BasePermission.

Use has_permission for general checks and has_object_permission for object-specific checks.

Examples
This permission allows access only if the user is staff (admin).
Django
from rest_framework.permissions import BasePermission

class IsAdminUser(BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_staff
This permission allows access only if the user owns the object.
Django
from rest_framework.permissions import BasePermission

class IsOwner(BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user
Sample Program

This example shows a custom permission that allows access only if the user owns the item. The view checks this permission before responding.

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

class IsOwnerPermission(BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user

class Item:
    def __init__(self, owner):
        self.owner = owner

class ItemView(APIView):
    permission_classes = [IsOwnerPermission]

    def get(self, request):
        item = Item(owner=request.user)
        self.check_object_permissions(request, item)
        return Response({'detail': 'You are the owner!'})
OutputSuccess
Important Notes

Always test your custom permissions to make sure they work as expected.

Use has_permission for general access and has_object_permission for checking specific objects.

Combine multiple permissions by listing them in permission_classes.

Summary

Custom permissions control user access in Django apps.

Create them by subclassing BasePermission and defining permission methods.

Use them in views to protect data and actions based on your rules.