suhkha
suhkha

Reputation: 581

Display results of query in user admin section - django

Newbie question:

I have my "users" app in the django admin but is there a way to implement a section that only shows users with criteria is_staff = False or any other criteria that I define? I'm a bit lost because I don't think it's necessary to create an app, because I don't need to create a new table, just query and display.

For example:

enter image description here

My query should I implement it in users / admin.py? But how do I render the result of the query?

Thanks!

Upvotes: 0

Views: 860

Answers (2)

Keyvan Khademi
Keyvan Khademi

Reputation: 116

You can define filters in the admin class. Then Django automatically creates a filter sidebar where you can filter the users.

@admin.register(User)
class UserAdmin(BaseUserAdmin):
    model = User
    list_filter = ('is_staff', )

For more information please look at the documentation.

Upvotes: 1

bolino
bolino

Reputation: 1122

You can override the get_queryset method from UserAdmin class with whatever request you want on your User table. For example, in your admin.py:

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

@admin.register(User)
class UserAdmin(BaseUserAdmin):
    model = User

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(is_staff=False)

You can even use some current user's attributes to request the data depending on it, like:

def get_queryset(self, request):
    qs = super().get_queryset(request)
    if not request.user.is_staff:
        return qs.filter(is_staff=False)
    return qs
        

Upvotes: 0

Related Questions