我在一個類中有一個m2m字段,並且有一個通過表。我不是表來保存通過表的項目列表。 如果我有一個多選擇的形式,像下面,我想要能夠保存所有選定的項目,我應該怎麼做?Django在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()
這可怎麼辦呢? 謝謝!
可能重複(http://stackoverflow.com/questions/3074938/django-m2m-form-save-through-table) – Lekensteyn 2014-08-23 16:16:58