Django 在 m2m 中间表中保存项目列表

发布于 2024-09-06 18:45:21 字数 1081 浏览 2 评论 0原文

我在一个类中有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不弃不离 2024-09-13 18:45:21

Django 应该像处理任何其他模型表单一样处理多对多模型表单。

当您在表单上使用简单的 save() 时,所有数据(包括多对多数据)都会被保存,而无需任何其他方法调用。

参考:

Django should handle many-to-many ModelForms just as any other model form.

When you use a simple save() on a form, all data -- including many-to-many data -- is saved without the need for any additional method calls.

Reference:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文