Skip to content

Instantly share code, notes, and snippets.

@vdboor
Last active March 29, 2021 11:10
Show Gist options
  • Save vdboor/6280390 to your computer and use it in GitHub Desktop.
Save vdboor/6280390 to your computer and use it in GitHub Desktop.
Patch Django admin to hide useless default permissions.Import this file somewhere in an `__init__.py` or `admin.py` file.
"""
Hide permission in the Django admin which are irrelevant, and not used at all.
"""
from django.contrib import admin
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.models import Group, User
class PermissionFilterMixin(object):
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field.name in ('permissions', 'user_permissions'):
qs = kwargs.get('queryset', db_field.remote_field.model.objects)
qs = _filter_permissions(qs)
kwargs['queryset'] = qs
return super(PermissionFilterMixin, self).formfield_for_manytomany(db_field, request, **kwargs)
class MyGroupAdmin(PermissionFilterMixin, GroupAdmin):
pass
class MyUserAdmin(PermissionFilterMixin, UserAdmin):
pass
admin.site.unregister(User)
admin.site.unregister(Group)
admin.site.register(User, MyUserAdmin)
admin.site.register(Group, MyGroupAdmin)
def _filter_permissions(qs):
return qs.exclude(codename__in=(
# Has no admin interface:
'add_permission',
'change_permission',
'delete_permission',
'add_contenttype',
'change_contenttype',
'delete_contenttype',
'add_session',
'delete_session',
'change_session',
# django.contrib.admin
'add_logentry',
'change_logentry',
'delete_logentry',
# sorl-thumbnail
'add_kvstore',
'change_kvstore',
'delete_kvstore',
# south
'add_migrationhistory',
'change_migrationhistory',
'delete_migrationhistory',
# django-admin-tools
'add_dashboardpreferences',
'change_dashboardpreferences',
'delete_dashboardpreferences',
'add_bookmark',
'change_bookmark',
'delete_bookmark',
)) \
.exclude(codename__endswith='userobjectpermission') \
.exclude(codename__endswith='groupobjectpermission') # django-guardian
@NiMeDia
Copy link

NiMeDia commented May 22, 2020

Just in case anyone needs this in Django 3, replace db_field.rel.to.objects with db_field.remote_field.model.objects

@vdboor
Copy link
Author

vdboor commented May 28, 2020

Just in case anyone needs this in Django 3, replace db_field.rel.to.objects with db_field.remote_field.model.objects

Thanks, I've updated the gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment