Bird
Raised Fist0
Djangoframework~10 mins

DRF permissions in Django - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - DRF permissions
Request Received
Check Permission Classes
Call has_permission()
Yes
Call has_object_permission() if object
Yes
Allow Access
No
Deny Access (Raise PermissionDenied)
When a request comes in, DRF checks permission classes by calling has_permission(), then has_object_permission() if needed, to decide if access is allowed or denied.
Execution Sample
Django
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response

class MyView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'msg': 'Hello'})
This code checks if the user is authenticated before allowing access to the GET method.
Execution Table
StepActionPermission Method CalledUser Authenticated?ResultAccess Outcome
1Request received for GET /myview/N/AN/AStart permission checkPending
2Check permission_classeshas_permission()TruePermission grantedPending
3No object-level permission neededN/AN/ASkip has_object_permissionPending
4Allow access to GET methodN/AN/AAccess allowedAccess Granted
5Return response {'msg': 'Hello'}N/AN/AResponse sentAccess Granted
6If user was not authenticatedhas_permission()FalsePermission deniedAccess Denied
💡 Access is granted only if has_permission() returns True; otherwise, access is denied.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
user.is_authenticatedUnknownTrueTrueTrue
permission_grantedFalseTrueTrueTrue
access_outcomePendingPendingAccess GrantedAccess Granted
Key Moments - 2 Insights
Why does DRF call has_permission() before has_object_permission()?
has_permission() checks general access like authentication before checking specific object permissions in has_object_permission(), as shown in steps 2 and 3 of the execution_table.
What happens if the user is not authenticated?
If user.is_authenticated is False, has_permission() returns False (step 6), and DRF denies access immediately without calling has_object_permission().
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of has_permission() when the user is authenticated?
APermission granted
BPermission denied
CNo permission check
DError raised
💡 Hint
Check step 2 in the execution_table where has_permission() is called with user authenticated.
At which step does DRF decide to allow access to the GET method?
AStep 1
BStep 4
CStep 3
DStep 6
💡 Hint
Look for the step where 'Allow access to GET method' happens in the execution_table.
If the user is not authenticated, which permission method causes access denial?
Apermission_classes attribute
Bhas_object_permission()
Chas_permission()
Dget() method
💡 Hint
See step 6 in the execution_table where has_permission() returns False.
Concept Snapshot
DRF Permissions check access by calling has_permission() first.
has_object_permission() runs only if object-level check is needed.
If any permission method returns False, access is denied.
Use permission_classes list to set permissions on views.
Common permission: IsAuthenticated checks user login.
Permissions protect API endpoints from unauthorized access.
Full Transcript
When a request comes to a Django REST Framework view, it checks permissions to decide if the user can access the resource. First, it calls has_permission() on each permission class to check general access like authentication. If the user passes this, and if the request targets a specific object, it calls has_object_permission() to check object-level rights. If any check fails, DRF denies access immediately. For example, the IsAuthenticated permission class returns True only if the user is logged in. This process ensures only authorized users can use the API endpoints.

Practice

(1/5)
1. What is the main purpose of permissions in Django REST Framework (DRF)?
easy
A. To control who can access or modify API endpoints
B. To style the API responses
C. To speed up database queries
D. To manage user sessions

Solution

  1. Step 1: Understand the role of permissions in DRF

    Permissions define rules about who can use or change API data.
  2. Step 2: Compare options with permissions purpose

    Only controlling access matches the purpose of permissions.
  3. Final Answer:

    To control who can access or modify API endpoints -> Option A
  4. Quick Check:

    Permissions = Access control [OK]
Hint: Permissions control access, not styling or speed [OK]
Common Mistakes:
  • Confusing permissions with styling or performance
  • Thinking permissions manage sessions
2. Which of the following is the correct way to apply the built-in permission IsAuthenticated to a DRF view?
easy
A. permissions = IsAuthenticated()
B. permission_classes = [IsAuthenticated]
C. permission_classes = IsAuthenticated
D. permission_classes = (IsAuthenticated)

Solution

  1. Step 1: Recall DRF permission syntax

    Permissions are set as a list or tuple in permission_classes.
  2. Step 2: Check each option's syntax

    permission_classes = [IsAuthenticated] uses a list with the class name, which is correct. permissions = IsAuthenticated() uses wrong attribute name and instance. permission_classes = IsAuthenticated misses list brackets. permission_classes = (IsAuthenticated) uses parentheses but without a comma, so it's not a tuple.
  3. Final Answer:

    permission_classes = [IsAuthenticated] -> Option B
  4. Quick Check:

    Use list for permission_classes [OK]
Hint: Use a list of permission classes for permission_classes [OK]
Common Mistakes:
  • Using instance instead of class in permission_classes
  • Forgetting to wrap in list or tuple
  • Using wrong attribute name
3. Given this DRF view snippet, what will happen if an anonymous user tries to access it?
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class MyView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'message': 'Hello'})
medium
A. The user will receive a 401 Unauthorized response
B. The user will see the message 'Hello'
C. The user will receive a 403 Forbidden response
D. The server will raise a syntax error

Solution

  1. Step 1: Understand IsAuthenticated permission behavior

    This permission denies access to anonymous users and returns 401 Unauthorized.
  2. Step 2: Analyze the code behavior for anonymous user

    Since the user is not logged in, DRF returns 401, not 403 or success.
  3. Final Answer:

    The user will receive a 401 Unauthorized response -> Option A
  4. Quick Check:

    IsAuthenticated denies anonymous with 401 [OK]
Hint: IsAuthenticated returns 401 for anonymous users [OK]
Common Mistakes:
  • Confusing 401 Unauthorized with 403 Forbidden
  • Expecting anonymous users to see data
  • Thinking code has syntax errors
4. Identify the error in this custom permission class:
from rest_framework.permissions import BasePermission

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

# Usage in view
class MyView(APIView):
    permission_classes = [IsOwner()]

    def get(self, request, pk):
        obj = get_object(pk)
        self.check_object_permissions(request, obj)
        return Response({'id': obj.id})
medium
A. get_object method is undefined
B. has_object_permission method is missing a return statement
C. check_object_permissions is called incorrectly
D. Permission class should be passed as class, not instance

Solution

  1. Step 1: Check how permission_classes should be set

    DRF expects permission classes, not instances, so use IsOwner without parentheses.
  2. Step 2: Review other parts for errors

    has_object_permission returns correctly, check_object_permissions usage is correct, get_object assumed defined elsewhere.
  3. Final Answer:

    Permission class should be passed as class, not instance -> Option D
  4. Quick Check:

    Use class names, not instances in permission_classes [OK]
Hint: Use class names, not instances, in permission_classes [OK]
Common Mistakes:
  • Passing permission instances instead of classes
  • Assuming missing return in has_object_permission
  • Confusing method calls with errors
5. You want to create a custom permission that allows access only if the user is authenticated and is the owner of the object. Which is the correct way to combine built-in and custom permissions in DRF?
hard
A. Set permission_classes = [IsAuthenticatedOrReadOnly, IsOwner] and override has_permission in IsOwner
B. Set permission_classes = [IsOwner] only and check authentication inside IsOwner
C. Set permission_classes = [IsAuthenticated, IsOwner] and implement has_object_permission in IsOwner
D. Set permission_classes = [IsAuthenticated()] and call IsOwner manually in the view

Solution

  1. Step 1: Understand combining permissions in DRF

    DRF checks all permissions in the list; all must allow access.
  2. Step 2: Check how to combine authentication and ownership

    Use IsAuthenticated to check login, and IsOwner to check object ownership via has_object_permission.
  3. Step 3: Evaluate options

    Set permission_classes = [IsAuthenticated, IsOwner] and implement has_object_permission in IsOwner correctly combines both permissions. Set permission_classes = [IsOwner] only and check authentication inside IsOwner misses separate authentication check. Set permission_classes = [IsAuthenticatedOrReadOnly, IsOwner] and override has_permission in IsOwner mixes permission types incorrectly. Set permission_classes = [IsAuthenticated()] and call IsOwner manually in the view uses instance and manual calls, which is not standard.
  4. Final Answer:

    Set permission_classes = [IsAuthenticated, IsOwner] and implement has_object_permission in IsOwner -> Option C
  5. Quick Check:

    Combine permissions in list for layered checks [OK]
Hint: List all needed permissions in permission_classes [OK]
Common Mistakes:
  • Skipping IsAuthenticated when ownership matters
  • Using instances instead of classes
  • Trying to call permissions manually