</>
Skip to content
Django lessons (42/43)

Django — Permissions

Built-in Permissions

PermissionDescription
AllowAnyAnyone can access
IsAuthenticatedMust be logged in
IsAdminUserMust be admin
IsAuthenticatedOrReadOnlyRead for anyone, write for authenticated

View-Level Permissions

from rest_framework.permissions import IsAuthenticated

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticated]

Custom Permission

from rest_framework.permissions import BasePermission

class IsOwnerOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.author == request.user

class PostViewSet(viewsets.ModelViewSet):
    permission_classes = [IsOwnerOrReadOnly]

Object-Level Permissions

def has_object_permission(self, request, view, obj):
    # Read permissions for any request
    if request.method in permissions.SAFE_METHODS:
        return True
    # Write permissions only to owner
    return obj.author == request.user

Global Permissions

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

Mini Practice

  1. Add authentication to API
  2. Create custom permission class
  3. Implement object-level permissions
  4. Set global permissions

Up Next

Continue with Routers — URL routing for ViewSets.

Related Topics

Frequently Asked Questions about Permissions

What is Permissions in Django?

Permissions is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Permissions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Permissions.

Why is Permissions important in Django?

Permissions is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.