django access control based on a model field value
Question: 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)


Answer: 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
    

