Django Admin - 根据组分配更改用户类型 (is_staff = T/F)

Django Admin - change user type (is_staff = T/F) based on group assignment

我有一个 Django 应用程序有 3 种类型的用户,super_user,管理员,用户。在 django-admin 面板中,我将一个用户分配给 Admin 组。管理员组是具有允许权限的组。因此,当我分配一个用户时,我在 GroupAdminForm 中将他们的 is_staff 更改为 True。问题是当我从组中删除用户时,我无法将这些用户 is_staff 更改为 false。这是我的 GroupAdminForm

我还看到 save_m2m 被调用了 2 次,但我只调用了一次。这里的储蓄流程是什么?

class GroupAdminForm(forms.ModelForm):
    class Meta:
        model = Group
        exclude = []

    users = forms.ModelMultipleChoiceField(
         queryset=User.objects.all(),
         required=False,
         widget=FilteredSelectMultiple('users', False)
    )

    def __init__(self, *args, **kwargs):
        super(GroupAdminForm, self).__init__(*args, **kwargs)
        old_users = None
        if self.instance.pk:
            self.fields['users'].initial = self.instance.user_set.all()
            old_users = self.instance.user_set.all()

    def save_m2m(self):
        print(f'Users = ', self.instance.user_set.all())
        print(f'M2M Called - {self.test}')
        self.instance.user_set.set(self.cleaned_data['users'])

    def save(self, *args, **kwargs):
        instance = super(GroupAdminForm, self).save()
        all_users = self.instance.user_set.all()
        print('Save Called')

        self.save_m2m()

        users = self.cleaned_data['users']
        if instance.name == 'Admin':
            for user in users:
                user.is_staff = True
                user.save()


        return instance


save_m2m is being called 2 times

save() 方法接受可选的 commit 关键字参数,该参数接受 TrueFalse (默认为 True)。如果您使用 commit=True 调用 save(),您的情况是:

instance = super(GroupAdminForm, self).save()

Django 会自动调用 save_m2m()Documentation 为防止使用 commit=False

 instance = super(GroupAdminForm, self).save(commit=False)

Problem is when I remove a user from the group I can not change those users is_staff to false

使用m2m_changed信号更新is_staff属性