Invalid Literal error when adding a user permission to a Django user object

喜欢而已 提交于 2019-12-18 05:00:12

问题


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"),
        )

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')

The code blows up with the following exception:

invalid literal for int() with base 10: 'foo.view_bar'

What's going on?


回答1:


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)

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.



来源:https://stackoverflow.com/questions/10131271/invalid-literal-error-when-adding-a-user-permission-to-a-django-user-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!