Django admin - change permission list

Is it possible to change the list of permissions on the edit page? I do not want to show all permissions, for example, an entry in the administrator log or auth group, etc. How to change the main query to exclude it?

+7
source share
2 answers

I got an idea from this topic that will also answer your question, but this is not so clear.

You must rewrite the user permission request in the UserAdmin form used for rendering.

To do this, the easiest way is to subclass UserAdmin and overwrite the get_form method:

 from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin class MyUserAdmin(UserAdmin): def get_form(self, request, obj=None, **kwargs): # Get form from original UserAdmin. form = super(MyUserAdmin, self).get_form(request, obj, **kwargs) if 'user_permissions' in form.base_fields: permissions = form.base_fields['user_permissions'] permissions.queryset = permissions.queryset.filter(content_type__name='log entry') return form 

You can change the filter of your request to whatever you want: Examples:

 # Exclude admin and auth. permissions.queryset = permissions.queryset.exclude(content_type__app_label__in=['admin', 'auth']) # Only view permissions of desired models (Can be your models or Django's) permissions.queryset = permissions.queryset.filter(content_type__model__in=['blog', 'post', 'user', 'group']) 

After creating your class, you must register your user model using your newly created Admin:

 admin.site.unregister(User) # You must unregister first admin.site.register(User, MyUserAdmin) 

Edit: I added a comment from Maik Hoepfel because this code caused django to crash when creating a new user.


You can do the same with the list of permissions on the group editing page, but you need to create another Administrator that exits GroupAdmin and change form.base_fields['user_permissions'] to form.base_fields['permissions']

+9
source

Renato's answer is almost perfect. The Django administrator adds the user a two-step process with the same form, and his code does not work with KeyError for "user_permissions" in the first step.

The fix is โ€‹โ€‹simple enough, just use the code below:

 def get_form(self, request, obj=None, **kwargs): form = super(MyUserAdmin, self).get_form(request, obj, **kwargs) # adding a User via the Admin doesn't include the permissions at first if 'user_permissions' in form.base_fields: permissions = form.base_fields['user_permissions'] permissions.queryset = permissions.queryset.filter(content_type__name='log entry') return form 
+4
source

All Articles