在创建用户时,我让表单附加了权限组。通常,用户和组绑定在ManyToMany关系中。因此,它正在生成MultipleChoiceField。但是,我希望只能为groups字段选择一个选项,而不是MultipleChoiceField。我已经为create User表单弄清楚了。但是对于更新用户表单,我如何调用组字段的初始值(或如何自动选择保存的值)。另外,还有没有比下面的代码更好的有效方法了?
创建用户表单:
class UserForm(forms.ModelForm):
email = forms.EmailField(required=True)
groups = forms.ChoiceField(required=False)
class Meta:
model = User
fields = ('username', 'email', 'groups')
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
choices = [[obj.pk, obj.name] for obj in Group.objects.all()]
choices.insert(0, ['', '--------'])
self.fields["groups"].choices = choices
更新用户表单:
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField(required=True)
groups = forms.ChoiceField(required=False)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'is_active', 'groups')
def __init__(self, *args, **kwargs):
super(UserUpdateForm, self).__init__(*args, **kwargs)
choices = [[obj.pk, obj.name] for obj in Group.objects.all()]
choices.insert(0, ['', '--------'])
self.fields["groups"].choices = choices
# My goal here is to call the initial value for the groups field which
# is ManyToManyField