Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 255
Chris B. Avatar asked Apr 12 '12 20:04

Chris B.


People also ask

How do I give permission to a specific user in Django?

through django-admin open your django-admin page and head to Users section and select your desired user . NOTE: Permission assigning process is a one-time thing, so you dont have to update it every time unless you need to change/re-assign the permissions.

How do I get user permissions in Django?

If you are using Django 3.0+, user. get_user_permissions() gives the codename of all the permissions.

How do I set permissions in Django?

With Django, you can create groups to class users and assign permissions to each group so when creating users, you can just assign the user to a group and, in turn, the user has all the permissions from that group. To create a group, you need the Group model from django. contrib. auth.

How do I give permission to admin in Django?

Test the 'view' permission is added to all models Using #3 for Django 1.7 only creates the permission objects if the model doesn't already exist. Is there a way to create a migration (or something else) to create the permission objects for existing models?


1 Answers

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.

like image 86
dgel Avatar answered Oct 09 '22 10:10

dgel