Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Change Fields in Group Admin Model

Tags:

python

django

The built-in django group model on the admin site only shows name:

enter image description here

but I want to include additional fields that are already part of the group model, such as id.

I have tried adding these fields using the following admin.py setup:

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


class GroupsAdmin(admin.ModelAdmin):
    list_display = ["name", "pk"]
    class Meta:
        model = Group

admin.site.register(Group, GroupsAdmin)

But this returns the error:

django.contrib.admin.sites.AlreadyRegistered: The model Group is already registered.

I have successfully registered other models (I've created) on admin but the above doesn't work for those models that are already a part of django.

How can I add fields in the admin model for Group?

like image 975
NickBraunagel Avatar asked Dec 18 '22 08:12

NickBraunagel


2 Answers

The accepted answer is correct, however, I would like to point out that you could inherit from the GroupAdmin if your goal is only extending that is, and not modifying:

from django.contrib.auth.admin import GroupAdmin

class GroupsAdmin(GroupAdmin):
    list_display = ["name", "pk"]

admin.site.unregister(Group)
admin.site.register(Group, GroupsAdmin)
like image 86
filtfilt Avatar answered Dec 20 '22 20:12

filtfilt


You need to unregister it first from the built-in Group model and then register it again with your custom GroupAdmin model.

So:

class GroupsAdmin(admin.ModelAdmin):
    list_display = ["name", "pk"]
    class Meta:
        model = Group

admin.site.unregister(Group)
admin.site.register(Group, GroupsAdmin)

Also, the Meta class is not required. You can remove it.

like image 25
nik_m Avatar answered Dec 20 '22 20:12

nik_m