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
- Limit Maximum Choices of ManyToManyField
- Django forms: how to dynamically create ModelChoiceField labels
- Upload direct to S3 or via EC2?
- Warnings (or even info messages) instead of only errors in Django
Source:stackexchange.com