djangopermissionsdjango-guardian

Django guardian user.has_perm false for existing data


I was trying to give permission using Django guardian. when I try to give permission for existing data its show me a false message but when I create a new object its show me true. what I'm doing wrong?

My code :

>>>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

But If I do

>>>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

Solution

  • excel = ExcelData.objects.all()
    

    will give you a queryset and

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

    will give you an object..

    You can only assign permission to an object

    if you want to assign permission for a queryset do it inside a loop

    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