17
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:
-
# adding permission ‘edit’ to a user ‘Bart’ on an instance of a MyObject from myapp.models
-
from django.contrib.auth.models import User, Group
-
from myapp.models import MyObject
-
user = User.objects.get(username=‘Bart’)
-
obj = MyObject()
-
obj.save()
-
user.add_row_perm(obj, ‘edit’)
-
user.has_row_perm(obj, ‘edit’)
-
True
-
user.has_row_perm(obj, ‘delete’)
-
False
-
-
# similar for groups
-
group = Group.objects.get(pk=1) # get first group in the db
-
group.add_row_perm(obj, ‘read’)
-
-
# now we’ll add the user to the group and he will inherit the ‘read’ permission
-
user.groups.add(group)
-
user.has_row_perm(obj, ‘read’)
-
True
-
-
# now to remove permission
-
user.del_row_perm(obj, ‘edit’)
-
user.has_row_perm(obj, ‘edit’)
-
False
-
-
# note that when you try to remove a permission from a user that is granted to him through group nothing changes
-
user.del_row_perm(obj, ‘read’)
-
user.has_row_perm(obj, ‘read’)
-
True


Leave a Reply