简体   繁体   English

Django管理界面如何只显示群成员?

[英]How to display only group members in the Django admin interface?

I've been developing a school application for allowing the principal and his teachers to analyze data.我一直在开发一个允许校长和他的老师分析数据的学校应用程序。 The principal needs to add his own people to the system.校长需要将自己的人添加到系统中。 I think using Django's admin panel would be a really good choice for that.我认为使用 Django 的管理面板将是一个非常好的选择。

Here, I am the superuser and the principal is the staff (who can manage things on the admin panel).在这里,我是超级用户,校长是员工(可以在管理面板上管理事物)。

As a superuser, I can see the following output:作为超级用户,我可以看到以下 output:

在此处输入图像描述

And here is the view for the staff:这是工作人员的观点:

在此处输入图像描述

I also have two groups (school one, school two) in the system:我在系统中也有两个组(学校一,学校二): 在此处输入图像描述

The principal (staff user) John Doe belongs to the group "School Two" which has the permissions of add/change/delete/view users.校长(职员用户)John Doe 属于“学校二”组,该组具有添加/更改/删除/查看用户的权限。

My question is how can I list the users for a staff to see only his group of people?我的问题是如何列出员工的用户以仅查看他的一群人? (no superuser and no other groups' people). (没有超级用户,也没有其他组的人)。

Let me share some source code I implemented to for this custom user admin view:让我分享一些我为这个自定义用户管理视图实现的源代码:

The forms.py file: forms.py 文件:

class UserAdminCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        User = get_user_model()
        model = User
        fields = ('email',)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserAdminCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.is_staff = True
        if commit:
            user.save()
        return user

class UserAdminChangeForm(forms.ModelForm):

      password = ReadOnlyPasswordHashField()

      class Meta:
         User = get_user_model()
         model = User
         fields = '__all__' #fields = ('email', 'password', 'is_active','is_staff', 'groups')

       def __init__(self, *args, **kwargs):
           super(UserAdminChangeForm, self).__init__(*args, **kwargs)
           f = self.fields.get('user_permissions', None)
           if f is not None:
              f.queryset = f.queryset.select_related('content_type')

       def clean_password(self):
              return self.initial["password"]

Here is the admin.py file这是 admin.py 文件

from django.contrib import admin
from .models import User
from .forms import UserAdminCreationForm, UserAdminChangeForm

class MyUserAdmin(admin.ModelAdmin):
      form = UserAdminChangeForm
      add_form = UserAdminCreationForm

      list_display = ('email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_email_verified')
      list_filter = ('is_staff', 'is_active', 'groups')
      readonly_fields = ('last_login', 'date_joined',)
      fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('first_name','last_name')}),
        ('Permissions', {'fields': ('is_active','is_staff', 'groups')}),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
    )
       add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name','last_name','email', 'password1', 'password2')}
         ),
    )
       search_fields = ('first_name', 'last_name', 'email',)
       ordering = ('email',)
       filter_horizontal = ()

admin.site.register(User, MyUserAdmin)

I am using Django 2.1.我正在使用 Django 2.1。 Again, how can I display users who belong to a certain group?同样,如何显示属于某个组的用户? For example, here in this case, when John Doe (staff) logged in as admin, he should only see himself (and in future other groups members) because he only belongs to "School Two".例如,在这种情况下,当 John Doe(员工)以管理员身份登录时,他应该只能看到他自己(以及将来的其他组成员),因为他只属于“二号学校”。

I would be glad if I can get some help with this.如果我能得到一些帮助,我会很高兴。

You can override the get_queryset method for the admin class like this;您可以像这样覆盖管理员 class 的get_queryset方法;

class MyUserAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        # Filter here by user group
        return qs.filter(groups__id__in=request.user.groups.all())

Docs for this are here;文档在这里; https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset

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

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