Creating custom permissions

We want students to be able to access the contents of the courses they are enrolled in. Only students enrolled in a course should be able to access its contents. The best way to do this is with a custom permission class. Django provides a BasePermission class that allows you to define the following methods:

  • has_permission(): View-level permission check
  • has_object_permission(): Instance-level permission check

These methods should return True to grant access or False otherwise. Create a new file inside the courses/api/ directory and name it permissions.py. Add the following code to it:

from rest_framework.permissions import BasePermissionclass IsEnrolled(BasePermission): def has_object_permission(self, request, ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.