Django监护人user.has_perm对于现有数据为false

时间:2019-06-30 05:38:42

标签: django permissions django-guardian

我试图使用Django Guardian授予权限。当我尝试授予现有数据权限时,它向我显示一条错误消息,但是当我创建一个新对象时,其向我显示真实。我在做什么错了?

我的代码:

>>>from django.contrib.auth.models import User
>>>from print.models import *
>>>from guardian.shortcuts import assign_perm
>>>user = User.objects.create(username='tanvir',password='antu')
>>>excel = ExcelData.objects.all()
>>>assign_perm('delete_exceldata', user, excel)
>>>user.has_perm('delete_exceldata', excel)
>>>False

但是如果我这样做

>>>from django.contrib.auth.models import User
>>>from print.models import *
>>>from guardian.shortcuts import assign_perm
>>>user = User.objects.create(username='tanvir',password='antu')
>>>excel = ExcelData.objects.create(order_number='01245632145214')
>>>assign_perm('delete_exceldata', user, excel)
>>>user.has_perm('delete_exceldata', excel)
>>>True

1 个答案:

答案 0 :(得分:1)

excel = ExcelData.objects.all()

将为您提供一个查询集和

excel=ExcelData.objects.create(order_number='1245632145214')

会给你一个对象。

您只能为对象分配权限

如果您想为查询集分配权限,请在循环内执行

user = User.objects.create(username='tanvir',password='antu')
excel = ExcelData.objects.all()
for obj in excel:
    assign_perm('delete_exceldata', user, obj)
    user.has_perm('delete_exceldata', obj) # this will give you status for each obj