It is a common need to have per-row (instance) permissions in a web application.

I’ve created a very simple and non intrusive module to help with that.

You can find the source code of the django-granular-permissions on Google Code here:

http://code.google.com/p/django-granular-permissions/

It’s fully functional, only thing missing are unittests and templatetag that would use the request.user provided by the session middleware context.

To use the package simply add it somewhere to your PYTHONPATH (ie. under your django project, or use

easy_install -U django-granular-permissions

to grab it from cheeseshop) and add the ‘django_granular_permissions’ to your INSTALLED_APPS in your projects settings.py

That’s it. From now on you can check, add and remove permissions for any instance of models class in your project like this:

Python [Show Plain Code]:
  1. # adding permission ‘edit’ to a user ‘Bart’ on an instance of a MyObject from myapp.models
  2.  from django.contrib.auth.models import User, Group
  3.  from myapp.models import MyObject
  4.  user = User.objects.get(username=‘Bart’)
  5.  obj = MyObject()
  6.  obj.save()
  7.  user.add_row_perm(obj, ‘edit’)
  8.  user.has_row_perm(obj, ‘edit’)
  9. True
  10.  user.has_row_perm(obj, ‘delete’)
  11. False
  12.  
  13. # similar for groups
  14.  group = Group.objects.get(pk=1) # get first group in the db
  15.  group.add_row_perm(obj, ‘read’)
  16.  
  17. # now we’ll add the user to the group and he will inherit the ‘read’ permission
  18.  user.groups.add(group)
  19.  user.has_row_perm(obj, ‘read’)
  20. True
  21.  
  22. # now to remove permission
  23.  user.del_row_perm(obj, ‘edit’)
  24.  user.has_row_perm(obj, ‘edit’)
  25. False
  26.  
  27. # note that when you try to remove a permission from a user that is granted to him through group nothing changes
  28.  user.del_row_perm(obj, ‘read’)
  29.  user.has_row_perm(obj, ‘read’)
  30. True