26

I have a group EuropartsBuyer and model named Product.

The following code adds a permission to the Product model.

class Meta:
        permissions = (
            ("can_add_cost_price", "Can add cost price"),
        )

In one of my views I have the following code to add this permission to that group.

europarts_buyer, created = Group.objects.get_or_create(name='EuropartsBuyer')
add_cost_price = Permission.objects.get(codename='can_add_cost_price')
europarts_buyer.permissions.add(add_cost_price)

With the help of Django Admin I have added a user to the group EuropartsBuyer.

When I use the following code in another view

if request.user.has_perm('can_add_cost_price'):
    do something

the result is supposed to be True but it is showing False. Thus, the code under the if clause doesn't run.

I have imported the currently logged in user in Django shell and when I test the permission again it shows False.

What am I doing wrong here?

ekad
  • 14,436
  • 26
  • 44
  • 46
MiniGunnR
  • 5,590
  • 8
  • 42
  • 66

2 Answers2

61

Try this:

if request.user.has_perm('app_name.can_add_cost_price'):

From the docs:

where each perm is in the format 'app_label.permission codename'

rrawat
  • 1,071
  • 1
  • 15
  • 29
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
-1

When you are working with permissions groups you don't need to check for each permission the user has. If the user is part of the permission group you created in the Django admin just change "YourGroupName" to the name your called your group when you created it

        {% ifequal user.groups.all.0.name "YourGroupName" %}
          <div>This is User</div>
        {% endifequal %}
cirsam
  • 11
  • 3
  • The zero limits you to check only one group. Also, the calculations in the view have been performed and you are checking too late if the server should perform something. Permissions are a way to even limit the server's overhead. – NFSpeedy Jul 02 '22 at 08:58