Creating custom permissions
You want students to be able to access the contents of the courses they are enrolled on. Only students enrolled on a course should be able to access its contents. The best way to do this is with a custom permission class. DRF provides a BasePermission
class that allows you to define the following methods:
has_permission()
: A view-level permission checkhas_object_permission()
: An 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()
You subclass the BasePermission
class and override the has_object_permission()
. You check that the user performing the request...