How To Get a List Of All User Permissions Available in Django Based Project
Django comes with a simple permissions system. It provides a way to assign permissions to specific users and groups of users. The system adds "change, remove and add" permissions automatically to every model class. And it's pretty easy to add custom permissions to a model class, like this:
1 2 3 4 5 6 7
And then you can check if the current user has permission:
1) be it inside Django template:
1 2 3
2) or inside python code, the most naive way is:
3) For more ways to check if user has a permission, please refer to Django docs: https://docs.djangoproject.com/en/1.11/topics/auth/default/#topic-authorization
You may have already noticed the pattern of how a permission gets registered: <app_name>.<permission_slug>.
And now the best part: while developing, you may get lucky and guess this pattern all the time, or you can scratch your head (like me) everytime you need to figure out what's the correct name of so much needed permission is.
I couldn't find a sane way of figuring out permission names easily, so I came up with a little management command that allows me to list all permissions available in the system, here's the code, please read my comments in the code if you want to understand what's happening:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
Put this code inside <your_django_app>/management/commands/get_all_permissions.py and then run python manage.py get_all_permissions
You should get a list of permissions that looks more or less like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Voila, now you have an easy lookup in user permissions.
I packaged this code into a little module called Django Debug Permissions and published it on PYPI.
Feel free to install it via PIP:
Github repo can be found here: https://github.com/timonweb/django-debug-permissions.