如何使用 Django 组和权限?

我了解基本的用户信息。我知道身份验证、登录、创建帐户等等。但是现在我想处理组和权限。

Django 组/权限的文档在哪里? 不是这个: http://docs.djangoproject.com/en/dev/topics/auth/

44911 次浏览

I suppose the first question you need to ask are what permissions do you need and what sort. By what sort, I mean do you want Model- or Object-level. To clarify the difference say you have a model Car. If you want to give permissions on all cars, then Model-level is appropriate, but if you want to give permissions on a per-car basis you want Object-level. You may need both, and this isn't a problem as we'll see.

For Model permissions, Django handles these for you... mostly. For each model Django will create permissions in the form 'appname.permissionname_modelname'. If you have an app called 'drivers' with the Car model then one permission would be 'drivers.delete_car'. The permissions that Django automatically creates will be create, change, and delete. For some strange reason they decided not to include read permissions from CRUD, you will have to do this yourself. Note that Django decided to change CRUD's 'update' to 'change' for some reason. To add more permissions to a 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 is a set of tuples, where the tuple items are the permission as described above and a description of that permission. You don't have to follow the permname_modelname convention but I usually stick with it.

Finally, to check permissions, you can use has_perm:

obj.has_perm( 'drivers.read_car' )

Where obj is either a User or Group instance. I think it is simpler 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

Where entity is the object to check permissions on (Group or User), model is the instance of a model, perms is a list of permissions as strings to check (e.g. ['read', 'change']), and app is the application name as a string. To do the same check as has_perm above you'd call something like this:

result = has_model_permissions( myuser, mycar, ['read'], 'drivers' )

If you need to use object or row permissions (they mean the same thing), then Django can't really help you by itself. The nice thing is that you can use both model and object permissions side-by-side. If you want object permissions you'll have to either write your own (if using 1.2+) or find a project someone else has written, one I like is django-objectpermissions from washingtontimes.