Using django permissions with django guardian (object level) permissions

For context, I am creating an e-learning website with 2 types of users: teachers and students.
I want to set model level permissions (for example, only teachers can create courses) as well as object level permissions (for example, a student can only submit his work on course instances he’s registered to, a student can only delete submission instances that he has created, a teacher can only view the submission instances of his students, etc.).

I can set model level permissions in django. But to set object level permissions I used django-guardian.

I have tried to set each type of permission separately, and they worked correctly. However, the problem i am facing is the following:

  • to enforce object level permissions in a view class, I need to use the PermissionRequiredMixin imported from guardian.shortcuts.
  • and to enforce the model level permissions in a view class I also need the PermissionRequiredMixin class with the same name, imported from django.contrib.auth.mixins.

I need both types of permissions to work together, so I need to import and use both classes in the same .py file, but since they have the same name, they are clashing and not working correctly.

What can i do in this case to make them work together?

You could do something like:

from guardian.shortcuts import PermissionRequiredMixin as GuardianPermissionRequiredMixin
from django.contrib.auth.mixins import PermissionRequiredMixin as DjangoPermissionRequiredMixin

Then you’d use the GuardianPermissionRequiredMixin and DjangoPermissionRequiredMixin in your code.

1 Like