Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 77 ยท REST APIs

DRF Permissions and Object-Level Permissions

Control who can do what in a Django REST Framework API: built-in permission classes, DjangoModelPermissions, DjangoObjectPermissions and a custom owner-only has_object_permission.

After authentication has decided who is calling, permissions decide whether that caller may do this. DRF runs permission checks right after authentication and before the view's action. A failing check returns 401 if the caller was not authenticated and an authentication header is available, or 403 otherwise.

A permission class is a tiny object with up to two hooks:

Method Runs Question it answers
has_permission(request, view) On every request, before the view May this user use this endpoint at all?
has_object_permission(request, view, obj) Only when the view calls self.get_object() May this user touch this particular row?

The second row is the one that surprises people, and it is the heart of this lesson. You can read more on Django's own authorization in Permissions, Groups and Authorization; DRF builds on the same auth_permission tables.

Built-in classes and combining them

Class Allows
AllowAny Everyone, including anonymous users
IsAuthenticated Any logged-in user
IsAdminUser Users with is_staff=True
IsAuthenticatedOrReadOnly Anyone to read (GET, HEAD, OPTIONS), authenticated users to write
DjangoModelPermissions Users who hold the model's add, change or delete permission
DjangoModelPermissionsOrAnonReadOnly The same, but anonymous reads are allowed
DjangoObjectPermissions Per-object permissions (needs an object-permission backend such as django-guardian)

Set a safe global default and relax it only where needed:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
}

A list means all of them must pass. You can also combine classes with & (and), | (or) and ~ (not):

Python
# read-only
permission_classes = [IsAuthenticated & (IsAdminUser | IsOwner)]
permission_classes = [~IsBlocked]

A custom, object-level owner permission

The most common custom rule is "anyone can read, only the owner can change." Write it once and reuse it. The example below defines IsOwnerOrReadOnly, applies it to a Note ViewSet and then shows the trap: object permissions are not applied to list responses. The list action never calls get_object(), so it never checks the rule for each row. You protect lists by filtering the queryset.

Python Owner-only editing with has_object_permission

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the two failing requests. Mia's edit and delete of Sam's note both returned 403 with the custom message, but the read of the same note was allowed, because SAFE_METHODS returns early. Also note that perform_create() sets the owner from request.user, and the owner the client tried to send was ignored since the field is read-only.

If notes should be private, an object permission is not enough. Anyone could still see them in the list. Make the queryset itself private with get_queryset(): return Note.objects.filter(owner=self.request.user). A row that is not in the queryset gives 404, which also avoids revealing that the row exists.

Model permissions: DjangoModelPermissions

Django's User and Group models already hold add_<model>, change_<model>, delete_<model> and view_<model> permissions (see the Permissions lesson). DjangoModelPermissions maps HTTP methods onto them:

Method Permission required
GET, HEAD, OPTIONS None (use a custom class if you need view_)
POST add
PUT, PATCH change
DELETE delete

This class needs a queryset attribute (or a get_queryset()), because it uses the model to build the permission names. It is a good fit when staff manage permissions in the admin, instead of coding a rule per role. Users must also be authenticated; DjangoModelPermissions denies anonymous users on writes.

Python DjangoModelPermissions with groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The "editors" group can create and update but not delete, exactly as the permission list says, and rita can do nothing. Because the rules live in the database, a staff member can change them in the admin without a deploy.

Per-object permissions

Django has no per-row permissions out of the box. DjangoObjectPermissions extends the model rules with checks on a specific object, but only works with a backend that stores object permissions; the most popular is the third-party package django-guardian. You install it, add its backend to AUTHENTICATION_BACKENDS, and grant permissions to individual users per row with assign_perm("change_note", user, note). For most apps a small custom class like IsOwnerOrReadOnly is simpler and faster, because it needs no extra tables. Reach for guardian when rows are shared with arbitrary users ("Mia lets Sam edit this one document").

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does DRF call has_object_permission()?

    Object permissions are checked inside get_object(), so detail actions use them and list actions do not. Protect lists by filtering the queryset.
  2. 2. What does permission_classes = [IsAuthenticated, IsOwnerOrReadOnly] mean?

    DRF requires every class in the list to pass. Use the | operator when either one should be enough.
  3. 3. How does DjangoModelPermissions treat a PATCH request?

    POST maps to add, PUT and PATCH to change and DELETE to delete.
  4. 4. Which approach keeps another user's notes out of a list entirely?

    Scoping the queryset removes foreign rows from lists and makes detail requests for them return 404, which also hides their existence.

Summary

  • Permission classes run after authentication; all classes in the list must pass, and &, |, ~ combine them.
  • has_permission() guards the endpoint; has_object_permission() guards one row and runs only through get_object().
  • Write an IsOwnerOrReadOnly class for owner rules, set the owner in perform_create(), and filter get_queryset() when rows must be private.
  • DjangoModelPermissions maps methods to Django's add/change/delete permissions so staff can manage access in the admin.
  • Use django-guardian only when you need true per-row grants to arbitrary users.

Next: Async Django.