Assign User-objects to a Group while editing Group-object in Django admin

后端 未结 4 966
鱼传尺愫
鱼传尺愫 2021-01-12 08:56

In the default Django admin view for user-object (edit user) one can edit the user\'s group memberships. What if I wanted this the other way around also? I.e. in the group e

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-12 08:59

    The save method above won't work if you add a new group and simultaneously add users to the group. The problem is that the new group won't get saved (the admin uses commit=False) and won't have a primary key. Since the purpose of save_m2m() is to allow the calling view to handle saving m2m objects, I made a save object that wraps the old save_m2m method in a new method.

    def save(self, commit=True):
        group = super(GroupAdminForm, self).save(commit=commit)
    
        if commit:
            group.user_set = self.cleaned_data['users']
        else:
            old_save_m2m = self.save_m2m
            def new_save_m2m():
                old_save_m2m()
                group.user_set = self.cleaned_data['users']
            self.save_m2m = new_save_m2m
        return group
    

提交回复
热议问题