Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: What is a permission codename?

Tags:

python

django

I'm trying to set up a permissions decorator in my Django app. The docs mention it and nowhere could I find explained what this codename represents (a model field? a model method? a permissions method?).

What is the codename and where can I setup codenames?

https://docs.djangoproject.com/en/1.9/topics/auth/default/#the-permission-required-decorator

like image 713
Proto Avatar asked Dec 18 '15 18:12

Proto


1 Answers

You can add custom permissions to any model under Meta class. Those permission name are called codename. It goes like this:

class Dish(models.Model):
    name = models.CharField()
    class Meta:
        permissions = (
            ('can_approve_dish', "Can approve Dish publication"),
            ('can_delete_dish', "Can Delete Dish")
        )

Here, can_approve_dish is a codename. Now, to perform any operation on Dish, you can check for permission like this:

# Assuming Dish model is under app named - `'app'`
if user.has_perm('app.can_delete_dish'):
    dish.delete()

These permissions would be available on admin site to be assigned to users after migration. So, if you haven't assigned a can_delete_dish permission to a user, he won't be able to delete that dish.

If you've added different permissions on multiple models under the app named - app, all those permissions will come under name app. That means, you've to have unique codename across models in the same app.

like image 125
Rohit Jain Avatar answered Sep 19 '22 03:09

Rohit Jain