I have a User Table in Django. It has different role values. I would like to show all user which role is based on a specific value.
I would like to show all user in Django admin panel which role is couple only.
In admin.py:
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from users.forms import UserChangeForm, UserCreationForm
from users.models import EmailConfirmationToken
User = get_user_model()
@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets
list_display = ["username", "name", "is_superuser", "is_active"]
search_fields = ["name", "subscription"]
I got the solution by customizing the queryset in ModelAdmin Class.
@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets
list_display = ["username", "name", "is_superuser", "is_active"]
search_fields = ["name", "subscription"]
def get_queryset(self, request):
qs = super(UserAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs.filter(role='couple')
return qs