Django:无法在指定中间模型的ManyToManyField上设置值

时间:2017-06-26 19:36:37

标签: python django python-3.x django-models django-forms

我在Django应用程序中遇到CreateView问题,我想创建一个Sesion,但会话只能由该组的GroupMember领导创建。

以下是我的模特:

class Group(models.Model):
    # The code

class GroupMember(models.Model):
    member = models.ForeignKey(Volunteer)
    group = models.ForeignKey(Group)
    leader = models.BooleanField(default=False)

class Session(models.Model):
    name = models.CharField(max_length=250)
    group = models.ForeignKey(Group)
    assistants = models.ManyToManyField(GroupMember, through='SessionAssistant')
    hours = models.FloatField(default=1)
    day = models.DateTimeField(default=datetime.now)

class SessionAssistant(models.Model):
    assistant = models.ForeignKey(GroupMember)
    session = models.ForeignKey(Session)
    rol = models.CharField(max_length=250)
    assist = models.BooleanField(default=True)

此外,我想在创建Sesision时可以分配我的助手,这是我的观点:

class CreateSession(CreateView):
    model = Session
    template_name = "session_form.html"
    fields = ['name',
              'hours',
              'day',
              'assistants', ]

    success_url = '/'

    def form_valid(self, form):
        group = Group.objects.get(id=self.kwargs['pk'])
        form.instance.group = group
        return super(CreateSession, self).form_valid(form)

1 个答案:

答案 0 :(得分:2)

Django不保存自定义ManyToMany关系。看看official documentation

您可以使用

保存表单
form.save()

然后从SessionAssistant

创建一个新对象
for assistant in form.cleaned_data['assistants']:
    SessionAssistant.objects.create(assistant=assistant, session=form.instance)