向Django用户对象添加用户权限时,文字错误无效 [英] Invalid Literal error when adding a user permission to a Django user object
问题描述
我在Django应用程序中定义了一个模型, foo
,如下所示:
I've got a model defined in my Django app foo
which looks like this:
class Bar(models.Model):
class Meta:
permissions = (
("view_bar", "Can view bars"),
)
我已经运行 manage.py syncdb
在这一点上,肯定地,它显示在 auth_permissions
表中:
I've run manage.py syncdb
on this, and sure enough, it shows up in the auth_permissions
table:
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')
该代码引起以下异常:
invalid literal for int() with base 10: 'foo.view_bar'
发生了什么?
推荐答案
user_permissions 。新增
正在添加一个ManyToMany管理器。所以你需要添加实际的Permission对象本身:
user_permissions.add
is adding to a ManyToMany manager. So you need to add the actual Permission object itself:
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)
另外,你可以当您进行测试时会感到奇怪,因为每个用户的权限也被缓存。您可能希望在调用 has_perm
之前删除缓存:
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
:
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.
这篇关于向Django用户对象添加用户权限时,文字错误无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!