我在一个类中有一个 m2m 字段和一个直通表。我不是表格来保存直通表格中的项目列表。如果我有一个多选表单,如下所示,并且我希望能够保存所有选定的项目,我应该怎么做?
我的模型形式如下所示:
class ClassroomForm(ModelForm):
class Meta:
model = Classroom
fields = ['classname','members','private']
def __init__(self, *args, **kwargs):
creator = kwargs.pop('user')
super(ClassroomForm, self).__init__(*args, **kwargs)
relations = Relations.objects.filter(initiated_by = creator)
self.fields["members"].queryset = \
User.objects.filter(pk__in=[r.follow.pk for r in relations])
我的保存方法是这样的:
def save_classroom(request):
classroom_instance = Classroom()
if request.method == 'POST':
form = ClassroomForm(request.POST, request.FILES, user = request.user)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.user = request.user
new_obj.save()
membership = Membership(member = HERE SELECTED ITEMS FROM FORM,classroom=new_obj)
membership.save()
如何做到这一点?谢谢!