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 BasePermission

class IsEnrolled(BasePermission):
def has_object_permission(self, request, view, obj):
return obj.students.filter(id=request.user.id).exists()

We subclass the BasePermission class and override the has_object_permission(). We check that the user performing the request is present in the students relationship of the Course object. We are going to use the IsEnrolled permission next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.247.11