gpt4 book ai didi

userAdmin 中的 Django user-to-groups 和 groupAdmin 中的 group-to-users

转载 作者:行者123 更新时间:2023-12-04 18:08:50 24 4
gpt4 key购买 nike

是否可以在用户选项卡的管理面板中使用多对多小部件来选择该用户所属的组,并在组选项卡中使用类似的多对多小部件来选择应该属于该组的用户?

最佳答案

有简单的方法和困难的方法。

简单的方法是使用 Django 的 InlineModelAdmin对象。但是,通过这种方式,您无法使用组小部件。

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)

困难的方法需要您构建自己的表单,手动加载和保存相关用户:
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.models import User, Group

class GroupForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(
label='Users',
queryset=User.objects.all(),
required=False,
widget=admin.widgets.FilteredSelectMultiple(
"users", is_stacked=False))

class Meta:
model = Group
exclude = () # since Django 1.8 this is needed
widgets = {
'permissions': admin.widgets.FilteredSelectMultiple(
"permissions", is_stacked=False),
}


class MyGroupAdmin(GroupAdmin):
form = GroupForm

def save_model(self, request, obj, form, change):
# save first to obtain id
super(GroupAdmin, self).save_model(request, obj, form, change)
obj.user_set.clear()
for user in form.cleaned_data['users']:
obj.user_set.add(user)

def get_form(self, request, obj=None, **kwargs):
if obj:
self.form.base_fields['users'].initial = [o.pk for o in obj.user_set.all()]
else:
self.form.base_fields['users'].initial = []
return GroupForm

# unregister and register again
admin.site.unregister(Group)
admin.site.register(Group, MyGroupAdmin)

关于userAdmin 中的 Django user-to-groups 和 groupAdmin 中的 group-to-users,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19748002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com