python Django Admin:隐藏UserAdmin的权限,为GroupAdmin排除无用的权限

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django Admin:隐藏UserAdmin的权限,为GroupAdmin排除无用的权限相关的知识,希望对你有一定的参考价值。

# coding: utf-8

from django.contrib import admin
from django.contrib.auth.models import Group, User
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.utils.translation import ugettext_lazy as _


class CustomUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups',)}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )


class CustomGroupAdmin(GroupAdmin):
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        if db_field.name == 'permissions':
            qs = kwargs.get('queryset', db_field.remote_field.model.objects)
            qs = qs.exclude(codename__in=(
                'add_permission',
                'change_permission',
                'delete_permission',

                'add_contenttype',
                'change_contenttype',
                'delete_contenttype',

                'add_session',
                'delete_session',
                'change_session',

                'add_logentry',
                'change_logentry',
                'delete_logentry',
            ))
            # Avoid a major performance hit resolving permission names which
            # triggers a content_type load:
            kwargs['queryset'] = qs.select_related('content_type')
        return super(GroupAdmin, self).formfield_for_manytomany(
            db_field, request=request, **kwargs)


admin.site.unregister(User)
admin.site.unregister(Group)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Group, CustomGroupAdmin)

以上是关于python Django Admin:隐藏UserAdmin的权限,为GroupAdmin排除无用的权限的主要内容,如果未能解决你的问题,请参考以下文章

Django admin 修改密码

如何在django-admin中隐藏特定记录的字段?

如何隐藏 django-admin 中的某些字段?

在 django admin 中禁用/隐藏不必要的内联表单

Django admin - 如何在用户编辑中隐藏一些字段?

试图在 django admin 中显示/隐藏 change_list 过滤器