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

前端 未结 1 363
悲哀的现实
悲哀的现实 2020-12-18 04:10

I\'ve got a model defined in my Django app foo which looks like this:

class Bar(models.Model):
    class Meta:
        permissions = (
                  


        
相关标签:
1条回答
  • 2020-12-18 04:46

    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.

    0 讨论(0)
提交回复
热议问题