简体   繁体   中英

Adding "group" field in Django User Admin

I am trying to add a "group" field to show group permissions on the user panel in Django 3.1.2. I tried combining this and this , but always end up in either The model User is already registered with 'auth.UserAdmin' or The model User is not registered (when trying to unregister first):

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']

How would I correctly register my custom UserAdmin?

I don't remeber, where I saw answer on SO, but do like: admin.site.unregister(User) before. Than modificate admin.model, as you wish, and then, register again.

from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin


admin.site.unregister(User)


class GroupInline(admin.StackedInline):
    model = Group


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    inlines = (GroupInline,)

If you want to show the group a user belong to in the list display:

@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'

and now in your list_display you can have it as this:

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

I hope this works for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM