简体   繁体   English

Django:按用户角色过滤用户

[英]Django: Filter users by user role

I am using the django admin site for my web app, but i am having a problem. 我正在为我的Web应用程序使用django管理站点,但是我遇到了问题。 I need that the staff users can change, create and delete another staff users, but i don't want that they change the informations of the superusers. 我需要工作人员用户可以更改,创建和删除其他工作人员用户,但我不希望他们更改超级用户的信息。 I want to know if is possible filter the user list by role (the staff user don't see the superusers in the list). 我想知道是否可以按角色过滤用户列表(职员用户在列表中看不到超级用户)。

Finally I found how to do this, I leave the code here just in case someone hav the same problem that I had 最后,我找到了解决方法,将代码留在这里,以防万一有人遇到与我同样的问题

def get_queryset(self, request):
    queryset = super(UserAdmin, self).get_queryset(request)
    if request.user.is_superuser:
        return queryset
    return queryset.filter(is_superuser=False)

You will need to create a custom ModelAdmin for the User model. 您将需要为用户模型创建一个自定义ModelAdmin。 I recommend you to inherit from the original one and then you can override the get_queryset method. 我建议您从原始方法继承,然后可以覆盖get_queryset方法。

You should end with: 您应该以:

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class MyUserAdmin(UserAdmin):

    def get_queryset(self, request):
        qs = super(MyUserAdmin, self).get_queryset(request)
        if request.user.is_superuser:
             return qs
        else:
             return qs.filter(is_superuser=False)

admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM