问题
It gives you filter by staff status and superuser status, but what about groups?
回答1:
Since version 1.3 it can be done using this:
list_filter = ('groups__name')
Of course as @S.Lott explains you must register your customized class in the admin.py file:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
list_filter = UserAdmin.list_filter + ('groups__name',)
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
回答2:
See Customizing an Admin form in Django while also using autodiscover
Essentially, you define a customized Admin class with the features you want.
Then unregister and register your revised Admin class.
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
回答3:
Here is a complete example, that inherits from SimpleListFilter, which is available in Django 1.4 and up.
https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
It support setting all available labels and parameters to create the completely custom filter.
It shows up as "By group" in the filter panel, with a list of all available groups.
from django.contrib.admin import SimpleListFilter
from django.contrib.auth.models import Group
from django.utils.translation import ugettext as _
class GroupListFilter(SimpleListFilter):
title = _('group')
parameter_name = 'group'
def lookups(self, request, model_admin):
items = ()
for group in Group.objects.all():
items += ((str(group.id), str(group.name),),)
return items
def queryset(self, request, queryset):
group_id = request.GET.get(self.parameter_name, None)
if group_id:
return queryset.filter(groups=group_id)
return queryset
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
list_filter = UserAdmin.list_filter + (GroupListFilter,)
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
回答4:
In later versions of Django, it works exactly as you'd expect:
list_filter = ('groups', )
No need to unregister/register the admin class.
来源:https://stackoverflow.com/questions/880684/in-django-admin-how-to-filter-users-by-group