Django 在 m2m 中间表中保存项目列表
我在一个类中有一个 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()
这是如何做到的? 谢谢!
I have a m2m field in a class, and a through table. I am not table to save the list of items from the through table.
if i have a multi select form, like below, and i want to be able to save all the selected items, how should i do it??
My model form looks like this:
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])
and my save method like this:
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()
How this can be done?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Django 应该像处理任何其他模型表单一样处理多对多模型表单。
参考:
Django should handle many-to-many ModelForms just as any other model form.
Reference: