Tuesday, 19 October 2021

How to setup Django permissions to be specific to a certain model's instances?

Please consider a simple Django app containing a central model called Project. Other resources of this app are always tied to a specific Project.

Exemplary code:

class Project(models.Model):
    pass

class Page(models.Model):
    project = models.ForeignKey(Project)

I'd like to leverage Django's permission system to set granular permissions per existing project. In the example's case, a user should be able to have a view_page permission for some project instances, and don't have it for others.

In the end, I would like to have a function like has_perm that takes the permission codename and a project as input and returns True if the current user has the permission in the given project.

Is there a way to extend or replace Django's authorization system to achieve something like this?

I could extend the user's Group model to include a link to Project and check both, the group's project and its permissions. But that's not elegant and doesn't allow for assigning permissions to single users.


Somewhat related questions on the Django forum can be found here:



from How to setup Django permissions to be specific to a certain model's instances?

No comments:

Post a Comment