Django — Permissions
Built-in Permissions
| Permission | Description |
|---|---|
| AllowAny | Anyone can access |
| IsAuthenticated | Must be logged in |
| IsAdminUser | Must be admin |
| IsAuthenticatedOrReadOnly | Read 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
- Add authentication to API
- Create custom permission class
- Implement object-level permissions
- 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.