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

后端 未结 4 1012
鱼传尺愫
鱼传尺愫 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 09:06

    Here is a simpler approach that uses Django's InlineModelAdmin objects (answered here on Qubanshi.cc)

    from django.contrib.auth.admin import GroupAdmin
    from django.contrib.auth.models import User, Group
    
    class UserSetInline(admin.TabularInline):
        model = User.groups.through
        raw_id_fields = ('user',)  # optional, if you have too many users
    
    class MyGroupAdmin(GroupAdmin):
        inlines = [UserSetInline]
    
    # unregister and register again
    admin.site.unregister(Group)
    admin.site.register(Group, MyGroupAdmin)
    

提交回复
热议问题