0

I have the following models:

Project:

class Project(models.Model):
    project_name = models.CharField(max_length=100, unique=True)

SearchCodes:

class SearchCode(models.Model):
   project = models.ForeignKey(Project, on_delete=models.CASCADE)
   search_code = models.CharField(max_length=3)
   search_code_modifier = models.CharField(max_length=1)

   class Meta:
     unique_together = ('project', 'search_code', 'search_code_modifier',)

From the Django-Guardian docs I am able to set permissions in the Django admin. Then for a Project I can check/restrict users in a view like so:

def project_edit(request, pk_project):

   project = get_object_or_404(Project, pk=pk_project)
   project_name = project.project_name

   user = request.user

   # Check user permission at the object level by passing in this specific project
   if user.has_perm('myApp.change_project', project):
      ...do something

Now here is where I am stuck. How do I set permissions on ANY SearchCodes that are related to a Project in the Django-Admin? I don't want to set object-level permissions on the SearchCodes - That would just be every instance of SearchCode. Rather I need to be able to set in the Admin:

You can view every SearchCode that is related to this Project BUT not any other SearchCodes.

Please let me know if I need to be more specific - I have tried to keep this as generic as possible.

Thank you - any help or pointers would be greatly appreciated.

EDIT:

I used the Admin-Integration example to set up the Project object-level permissions in Django-Guardian.

It feels like at this point there must be some way to set the permissions for all SearchCodes that are related to this particular instance of Project while I am in the Object-Permissions page for this Project.

beginAgain
  • 211
  • 4
  • 17

1 Answers1

1

Django-guardian is object level permission application, so assign permission on object which carry permission and check on that object for permission. In you particular example you have to write something like that to check permissions for code through project (permission carry object):

def code_edit(request, pk):

   code = get_object_or_404(SearchCode.objects.select_related('project'), pk=pk)
   project = code.project
   project_name = project.project_name

   user = request.user

   # Check user permission at the object level by passing in this specific project
   if user.has_perm('myApp.change_project', project):
      ...do something
Adam Dobrawy
  • 1,145
  • 13
  • 14
  • Thank you for your response. This is very helpful (+1) for checking permissions after they have been set - but I am looking for pointers/tutorial etc. about how to set the permissions on SearchCodes in the Django-Admin. Although I guess I probably can use this concept and roll my own permissions at the SearchCode level - I would rather do it in the admin - for the users sake and consistency :) – beginAgain Feb 21 '17 at 13:05