0

我正在尝试添加一个“组”字段以在 Django 3.1.2 的用户面板上显示组权限。我尝试将thisthis结合起来,但总是以The model User is already registered with 'auth.UserAdmin'or结束The model User is not registered(尝试先注销时):

from django.contrib import admin
from django.contrib.auth.models import User

# fails in "model User not registered"
admin.site.unregister(User) 

#fails in already registered with auth.UserAdmin
@admin.register(User) 
class UserAdmin(admin.ModelAdmin):
    def group(self, user):
        return ' '.join([g.name for g in user.groups.all()])

    list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', group]
    list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active']

我将如何正确注册我的自定义 UserAdmin?

4

1 回答 1

-1

如果要在列表显示中显示用户所属的组:

@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
def group(self, user):
    groups = []
    for group in user.groups.all():
        groups.append(group.name)
    return ' '.join(groups)
    group.short_description = 'Group'

现在在您的 list_display 中,您可以这样:

list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', 'group']

我希望这对你有用

于 2020-11-25T07:50:09.263 回答