How to prevent Django Admin users from changing the profile data of other Admin users?

I have an Admin User extended / subclassed by a teacher class.

How to prevent Teachers from viewing and changing the profile data of other Teachers, and Teachers can only change their records / lines? Thanks in advance!

+4
source share
3 answers

I'm not sure that I understand exactly what you are trying to do, but if you have built-in user administration pages that work a little different for teacher users, then I believe that you just need to extend UserAdmin and override the queryset method.

 class TeacherSpecificUserAdmin(UserAdmin): def queryset(self, request): if request.user.is_teacher(): return Teacher.objects.filter(pk=request.user.pk) return UserAdmin.queryset(self, request) 

This will take care of Teacher’s refusal to edit or delete other entries, because if you look in the ModelAdmin code, the change_view and delete_view use the query returned by the queryset method to get the object changed or deleted.

One more setting is necessary, since the view used to change the password in UserAdmin does not use the same system as the others to get the object to change. Just override it in the new class:

 ... def user_change_password(self, request, id): if request.user.is_teacher() and request.user.pk != int(id): # PermissionDenied is in django.core.exceptions raise PermissionDenied return UserAdmin.user_change_password(self, request, id) ... 

After that, you just need to prevent Teachers from adding new users or deleting their own account. Do this either using the standard django permission framework , or by overriding the has_add_permission and has_delete_permission .

Look in the source code for ModelAdmin if you want more information (in contrib/admin/options.py ).

+6
source

There is probably no way to build this.

See permission documents :

Permissions are set globally for each type of object, and not for a specific instance of the object. For example, you can say that “Mary can change news stories,” but it’s currently impossible to say “Mary can change news stories, but only those that she herself created” or “Mary can only change news with a certain status, publication date or identifier. " The latest functionality is what Django developers are talking about right now.

However, object level permissions seem to be.

+3
source

There is currently no easy way to do this, but object-level permissions will be available soon in Django 1.2 - although you need to make some work to get it working as an administrator.

Fortunately, there is an article in the Django Advent article that explains what you need to do.

+1
source

Source: https://habr.com/ru/post/1301542/


All Articles