Last active
March 29, 2021 11:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 |
@rohitpujar: correct, that was the whole point of this code - to hide those permissions. Easier then hacking the Django models.
Just in case anyone needs this in Django 3, replace db_field.rel.to.objects
with db_field.remote_field.model.objects
Just in case anyone needs this in Django 3, replace
db_field.rel.to.objects
withdb_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
This only hides the permissions, and when you run syncdb, the entries will be added back to the database!