pythondjangodjango-modelspermissionsdjango-views

Permission matching query does not exist in custom permission


try:
        user = User.objects.get(username = 'xyz')
        custom_permission = Permission.objects.get(codename='is_custom')
        user.user_permissions.add(custom_permission)
        user.save()
        print user.has_perm("is_custom")
        print user.has_perm('app.is_custom')
        user.get_all_permissions()

    except Exception as e:
        print(">>>>>",e)

I have done this simple thing to check the user custom permission but it rises the exception

DoesNotExist('Permission matching query does not exist.')

what's wrong in this ??


Solution

  • get should return the above error if no Model object satisfies the given condition. ie, there is no Permission object with the codename is_custom. You have to modify your query like,

    custom_permission = Permission.objects.filter(codename='is_custom').first() # return Permission object if exists else None
    if custom_permission:
        user.user_permissions.add(custom_permission)
        user.save()