我使用has_perm
方法通过id获取用户时遇到问题。应该返回true,因为我使用
usr.user_permissions.add(p)
我刷新用户对象再次通过id获得,但仍然返回false。即使出现在管理员中也是如此。如果有人知道别的东西。在这里,我保留了部分设置,用户模型和使用的代码示例
class User(AbstractUser):
name = models.CharField(max_length=50)
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
***********************设置***********************
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_filters',
'administration',
'work',
'bank',
'providers',
'customers',
'users',
]
************************代码示例********************* >
url = reverse_lazy('user:list', kwargs={'id': self.kwargs['user']})
user_obj = User.objects.get(id =self.kwargs['user'])
perm = Permission.objects.get(id =self.kwargs['perm'])
if user_obj.has_perm(perm):
print("removed")
user_obj.user_permissions.remove(perm)
else:
print("add")
user_obj.user_permissions.add(perm)
success_message = "User perm changed"
return HttpResponseRedirect(url)