I've got a model defined in my Django app foo
which looks like this:
我在我的Django app foo中定义了一个模型,如下所示:
class Bar(models.Model):
class Meta:
permissions = (
("view_bar", "Can view bars"),
)
I've run manage.py syncdb
on this, and sure enough, it shows up in the auth_permissions
table:
我在这上面运行了manage.py syncdb,果然,它出现在auth_permissions表中:
id|name|content_type_id|codename
41|Can view bars|12|view_bar
However, when I try adding that permission to a user object in a view, like so:
但是,当我尝试将该权限添加到视图中的用户对象时,如下所示:
request.user.user_permissions.add('foo.view_bar')
The code blows up with the following exception:
代码爆炸,出现以下异常:
invalid literal for int() with base 10: 'foo.view_bar'
What's going on?
这是怎么回事?
1 个解决方案
#1
11
user_permissions.add
is adding to a ManyToMany manager. So you need to add the actual Permission object itself:
user_permissions.add正在添加到ManyToMany管理器。所以你需要添加实际的Permission对象本身:
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(Bar)
permission = Permission.objects.get(content_type=content_type, codename='view_bar')
request.user.user_permissions.add(permission)
Also, you may experience weirdness when you're testing because permissions are also cached for each user. You may want to delete the cache before you call has_perm
:
此外,您在测试时可能会遇到奇怪现象,因为还会为每个用户缓存权限。您可能希望在调用has_perm之前删除缓存:
if hasattr(user, '_perm_cache'):
delattr(user, '_perm_cache')
In general, you probably want to write a bunch of helper methods that take care of all of this stuff so you can give and revoke permissions easily programatically. How you do so would really depend on how you're using the permissions.
通常,您可能希望编写一组辅助方法来处理所有这些内容,以便您可以轻松地以编程方式提供和撤消权限。你如何这样做真的取决于你如何使用权限。
#1
11
user_permissions.add
is adding to a ManyToMany manager. So you need to add the actual Permission object itself:
user_permissions.add正在添加到ManyToMany管理器。所以你需要添加实际的Permission对象本身:
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(Bar)
permission = Permission.objects.get(content_type=content_type, codename='view_bar')
request.user.user_permissions.add(permission)
Also, you may experience weirdness when you're testing because permissions are also cached for each user. You may want to delete the cache before you call has_perm
:
此外,您在测试时可能会遇到奇怪现象,因为还会为每个用户缓存权限。您可能希望在调用has_perm之前删除缓存:
if hasattr(user, '_perm_cache'):
delattr(user, '_perm_cache')
In general, you probably want to write a bunch of helper methods that take care of all of this stuff so you can give and revoke permissions easily programatically. How you do so would really depend on how you're using the permissions.
通常,您可能希望编写一组辅助方法来处理所有这些内容,以便您可以轻松地以编程方式提供和撤消权限。你如何这样做真的取决于你如何使用权限。