[Solved]-Display user group in admin interface?

12πŸ‘

βœ…

It is not possible by default because of the ManyToMany relation but this should work:

def group(self, user):
    groups = []
    for group in user.groups.all():
        groups.append(group.name)
    return ' '.join(groups)
group.short_description = 'Groups'

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'group')
# The last argument will display a column with the result of the "group" method defined above

You can test it and organize the code to your convenience.

πŸ‘€Alexis N-o

4πŸ‘

this can help

admin.py

from django.contrib.auth.admin import UserAdmin

from django.contrib.auth.models import User

class UserAdminWithGroup(UserAdmin):
    def group_name(self, obj):
        queryset = obj.groups.values_list('name',flat=True)
        groups = []
        for group in queryset:
            groups.append(group)
        
        return ' '.join(groups)

    list_display = UserAdmin.list_display + ('group_name',)

admin.site.unregister(User)
admin.site.register(User, UserAdminWithGroup)
πŸ‘€Muhammadoufi

-1πŸ‘

After reading about ManyToMany fields in admin list_display, it doesn’t seem like it’s possible without adding custom model methods.

Although, it looks like adding custom methods to built-in Django models is possible, if you do something like this:

from django.contrib.auth.models import User

class UserMethods(User):
  def custom_method(self):
    pass
  class Meta:
    proxy=True

proxy=True being the statement that tells django not to override the original model.

After that, just import your custom model method that gets the groups that are associated with the user and add it to your admin class.

πŸ‘€joshchandler

Leave a comment