class GroupMemberForm(forms.ModelForm):
# users 并非是 Group 对象的属性
# 这里使用ModelFrom对象的原因在于我们需要获得组对象
# Field disbaled is introduced in Django 1.9
# https://docs.djangoproject.com/en/1.9/ref/forms/fields/#disabled
name = forms.CharField(
label='组名', disabled=True, widget=forms.TextInput({'class': 'form-control'}))
users = ModelMultipleChoiceField(
label='组成员', required=False, queryset=User.objects.exclude(username='admin'),
widget=forms.SelectMultiple(choices=User.objects.exclude(username='admin')))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 获得组成员
user_ids = []
if kwargs.get('instance'):
group = kwargs['instance']
for user in group.user_set.all():
user_ids.append(user.id)
users = User.objects.filter(id__in=user_ids)
self.initial['users'] = users
def save(self, commit=True):
group = super().save(commit=False)
# 每次提交时都已当前用户选择的组成员为准
group.user_set.clear()
users = self.cleaned_data['users']
for user in users:
user.groups.add(group)
user.save()
group.save()
class Meta:
model = Group
exclude = ('permissions', )
如果不是在admin里的话,可以自己写一个Form
前端再挑一个通用的组件 http://www.virtuosoft.eu/code...
这事基本就解决了
django amdin里的那个组件不是那么容易被第三方使用