问题描述
如何在更改组的Django管理界面中将用户添加到组中?
How can I add users to a group in Django admin interface of "Change Group"?
我已经看到肮脏的骇客,使其可以在较早的django版本上使用。
I have seen dirty hacks to get this working for older django version.
如何使用Django 1.10解决此问题?
How to solve this with Django 1.10?
强调:我想要在更改组页面上,而不是更改用户。
Emphasize: I want this on the page "Change Group", not on "Change User".
我想使用django-admin风格的代码:无需编码,只需进行一些配置即可。也许是这样的:
I would like to have this in django-admin-style: No coding, just doing some configuration. Maybe like this:
class GroupAdmin(admin.ModelAdmin):
show_reverse_many_to_many = ('user',)
推荐答案
您需要编写 some 代码。请注意,Django管理站点是正常的Django视图和表单!
You need to write some code. Note that the Django admin site is normal Django views and forms!
首先创建一个ModelForm:
First create a 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
我们添加了一个自定义的Group ModelForm。第二步是注销原始组管理员并注册一个显示我们的ModelForm的新组管理员:
We added a custom Group ModelForm. The second step is to unregister the original Group admin and register a new Group admin that displays our 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)
这篇关于Django:通过Django Admin将用户添加到群组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!