I guess the first question you need to ask is what kind of permissions do you need and what kind. By what type, I mean, do you want a model or an object-level. To clarify the difference, say you have a model car. If you want to provide permissions for all cars, then the model level is suitable, but if you want to provide permissions for each car, you need an Object-level. You may need both, and this is not a problem, as we shall see.
For model permissions, Django handles them for you ... basically. For each model, Django will create permissions in the form "appname.permissionname_modelname". If you have an application called “drivers” with a car model, then one permission will be “drivers.delete_car”. The permissions that Django automatically creates will create, modify, and delete. For some strange reason, they decided not to include read permissions from CRUD, you have to do it yourself. Note that for some reason, Django decided to change CRUD 'update' to 'change'. To add additional permissions for the model, say read permissions, you use the Meta class:
class Car( models.Model ): # model stuff here class Meta: permissions = ( ( "read_car", "Can read Car" ), )
Note that permissions are a set of tuples where the elements of the set are a permission, as described above, and a description of that permission. You do not have to follow the permname_modelname convention, but I usually stick to it.
Finally, to check permissions, you can use has_perm:
obj.has_perm( 'drivers.read_car' )
If obj is an instance of a user or group. I think it’s easier to write a function for this:
def has_model_permissions( entity, model, perms, app ): for p in perms: if not entity.has_perm( "%s.%s_%s" % ( app, p, model.__name__ ) ): return False return True
If the object is an object for checking access rights (group or user), the model is an instance of the model, perms is a list of permissions as strings for checking (for example, ['read', 'change']) and app is the application name as a string . To perform the same check as has_perm above, you call something like this:
result = has_model_permissions( myuser, mycar, ['read'], 'drivers' )
If you need to use the permissions of objects or strings (they mean the same thing), then Django cannot really help you yourself. The nice thing is that you can use both the permissions of the model and the rights of the object side by side. If you need object rights, you will either have to write your own (when using 1.2+) or find a project that someone else wrote, one I like django-objectpermissions from washingtontimes.