4

I have a model class Department with a field name. I have another Model Student with a foreign key to Department. I want to control access to Student objects based on department. That is, a user with permission to edit the department with name "CS" can only edit that fields. How this can be achieved in Django? (I'm using django 1.8, python3)

Edit

class Department(models.Model):
    name = models.CharField(_('department name'), max_length=255)

class Students(models.Model):
    first_name = models.CharField(_('first name'), max_length=30)
    last_name = models.CharField(_('last name'), max_length=30)
    department = models.ForeignKey('Department')

Also I'm creating required permissions dynamically while adding new department.(eg: if department.name for new entry is 'CS', 2 permissions like 'view_CS' and 'edit_CS' will be created)

Rohith
  • 1,301
  • 3
  • 21
  • 31

2 Answers2

5

Based on http://django-guardian.readthedocs.org/en/v1.2/userguide/assign.html#for-group

class Department(models.Model):
    name = models.CharField(_('department name'), max_length=255)

    class Meta:
         permissions = (
             ('view', 'View department'),
             ('edit', 'Edit department'),
         )

Somewhere in views:

from django.contrib.auth.models import Group

cs_department = Department.objects.get(name='cs_department')
cs_department_group = Group.objects.create(name=cs_department.name)

assign_perm('view', cs_department_group, cs_department)
assign_perm('edit', cs_department_group, cs_department)

request.user.groups.add(cs_department_group)

print(request.user.has_perm('view', cs_department)) # True
print(request.user.has_perm('edit', cs_department)) # True
madzohan
  • 11,488
  • 9
  • 40
  • 67
-1

Since my application is pretty big, I cannot afford changing entire data references to accomodate the permissions as @madaohan's answer.

This kind of access control mechanisms can be easily used defining a custom model manager(docs) and a middleware to get logged in user object in models(Check this link),

Community
  • 1
  • 1
Rohith
  • 1,301
  • 3
  • 21
  • 31
  • I do not understand what you mean with "changing entire data references to accomodate the permissions". Also it is not clear how your links could help to solve your problems. Self accepting such a weak answer smells fishy. – tobltobs Apr 09 '16 at 19:51
  • I done it with custom model managers. The first link is django's docs for custom model managers. To get user info in model manager, I had to use a middleware (refer 2nd link). It solved my issue, that's why I wrote it here and self accepted it. Anyway I changed acceptance for this answer. @tobltobs what I meant with "changing entire data references to accomodate the permissions" is, I was not in a position to change each and every db accessing code to add permissions, so I used a custom model manager. – Rohith Apr 10 '16 at 03:22