S
S
Sergey Nizhny Novgorod2016-01-19 17:34:24
Django
Sergey Nizhny Novgorod, 2016-01-19 17:34:24

How to work with permissions in Django?

Hello.
Task:
There is a user, he does some specific action (for example, pokes a button), gets rights, watches the content.
Implementation:
Create a group
Add a unique right to it
Add a user to this group
Check this right.
Could someone throw off the code for an example, how to do each of these actions? Rummaged in the documentation, there it is a little not clearly stated about the given moment.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2016-01-19
@Terras

from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(YourModel)
my_permission = Permission.objects.create(codename='your_permission', 
                                          name='Can access something', 
                                          content_type=content_type)
my_group = Group.objects.create(name='My Group')
my_group.permissions = [my_permission]
user.groups.add(my_group)
user.has_perm('app_label.your_permission')  # True

I just don’t understand why there is a group here, if permissions can be added directly to the user. Individually.

M
mukhtar, 2021-06-03
@mukhtar

Look at this article.
https://gadjimuradov.ru/post/django-permissions-up...
It is described here for beginners

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question