CreateView不保存相关对象

时间:2018-02-10 15:34:00

标签: python django

我有两个模特:学生和小组。一个小组由多个学生组成,学生只能在一个小组中。以下是模型:

class Group(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Student(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    section = models.PositiveSmallIntegerField(default=1)
    group = models.ForeignKey(
        Group, on_delete=models.SET_NULL, null=True, blank=True
    )

我正在尝试构建一个表单,我可以选择多个学生来创建一个组。

class CreateGroupForm(forms.ModelForm):
    students = forms.ModelMultipleChoiceField(
        required=True,
        queryset=Student.objects.all()
    )

    class Meta:
        model = Group
        fields = ('students', )

我使用以下视图作为表单:

class SelectGroup(CreateView):
    model = Group
    form_class = CreateGroupForm
    template_name = 'selection.html'
    success_url = reverse_lazy('test')

当我提交表单时,它会创建一个组,但该组的student_set为空。我猜这是因为我不能在不先保存组的情况下将学生添加到组中。有没有办法让我修改这个视图来保存学生,或者我应该使用别的东西吗?

1 个答案:

答案 0 :(得分:2)

由于students不是群组模型的字段,因此模型表单save不知道如何处理它。您必须覆盖save方法并手动处理students字段:

class CreateGroupForm(forms.ModelForm):
    # ...
    def save(self, commit=True):
        # you have to commit, else the reverse fk has nothing to point to
        group = super(CreateGroupForm, self).save(commit=True)
        group.student_set.add(*self.cleaned_data['students'])
        return group

如果您不想删除表单上的非提交保存选项,您还可以覆盖视图的form_valid方法:

class SelectGroup(CreateView):
    # ...
    def form_valid(self, form):
        self.object.student_set.add(*self.form.cleaned_data['students'])
        return super(SelectGroup, self).form_valid(form)