gpt4 book ai didi

Django:通过 Django Admin 将用户添加到组

转载 作者:行者123 更新时间:2023-12-02 09:32:47 24 4
gpt4 key购买 nike

如何在 Django 管理界面的“更改组”中将用户添加到组中?

我见过一些肮脏的黑客行为,让这个功能适用于旧的 django 版本。

如何使用 Django 1.10 解决这个问题?

强调:我希望它出现在“更改组”页面上,而不是“更改用户”页面上。

我想以 django-admin-style 的方式实现:无需编码,只需进行一些配置。也许是这样的:

class GroupAdmin(admin.ModelAdmin):
show_reverse_many_to_many = ('user',)

最佳答案

您需要编写一些代码。请注意,Django 管理站点是普通的 Django View 和表单!

首先创建一个ModelForm:

from django import forms
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import Group


User = get_user_model()


# Create ModelForm based on the Group model.
class GroupAdminForm(forms.ModelForm):
class Meta:
model = Group
exclude = []

# Add the users field.
users = forms.ModelMultipleChoiceField(
queryset=User.objects.all(),
required=False,
# Use the pretty 'filter_horizontal widget'.
widget=FilteredSelectMultiple('users', False)
)

def __init__(self, *args, **kwargs):
# Do the normal form initialisation.
super(GroupAdminForm, self).__init__(*args, **kwargs)
# If it is an existing group (saved objects have a pk).
if self.instance.pk:
# Populate the users field with the current Group users.
self.fields['users'].initial = self.instance.user_set.all()

def save_m2m(self):
# Add the users to the Group.
self.instance.user_set.set(self.cleaned_data['users'])

def save(self, *args, **kwargs):
# Default save
instance = super(GroupAdminForm, self).save()
# Save many-to-many data
self.save_m2m()
return instance

我们添加了自定义组模型表单。第二步是取消注册原始组管理员并注册一个显示我们的 ModelForm 的新组管理员:

# Unregister the original Group admin.
admin.site.unregister(Group)

# Create a new Group admin.
class GroupAdmin(admin.ModelAdmin):
# Use our custom form.
form = GroupAdminForm
# Filter permissions horizontal as well.
filter_horizontal = ['permissions']

# Register the new Group ModelAdmin.
admin.site.register(Group, GroupAdmin)

Screenshot Django custom form and filter_horizontal in Group admin

关于Django:通过 Django Admin 将用户添加到组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39485067/

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