[英]CreateView doesn't save related objects
I have two models: Student and Group. 我有两个模型:学生模型和小组模型。 A group consists of multiple students and a student can be in only one group. 一组由多个学生组成,一个学生只能在一个组中。 Here are the models: 这些是模型:
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
)
I am trying to build a form where I can select multiple students to create a group. 我正在尝试建立一个表格,在这里我可以选择多个学生来创建一个小组。
class CreateGroupForm(forms.ModelForm):
students = forms.ModelMultipleChoiceField(
required=True,
queryset=Student.objects.all()
)
class Meta:
model = Group
fields = ('students', )
I am using the following view for the form: 我在表格中使用以下视图:
class SelectGroup(CreateView):
model = Group
form_class = CreateGroupForm
template_name = 'selection.html'
success_url = reverse_lazy('test')
When I submit the form, it creates a group but the group's student_set is empty. 当我提交表单时,它将创建一个组,但该组的student_set为空。 I am guessing this is because I cannot add students to a group without saving the group first. 我猜这是因为如果不先保存组,就无法将学生添加到组中。 Is there a way for me to modify this view to save the students or should I use something else? 我是否可以修改此视图以保存学生,还是应该使用其他方法?
Since students
is not a field of the group model, the model form's save
does not know what to do with it. 由于students
不是小组模型的一个领域,因此模型表单的save
不知道该如何处理。 You have to override the save
method and handle the students
field manually: 您必须重写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
If you prefer not to remove the non-commit save option on the form, you can also override the form_valid
method of the view: 如果您不想在表单上删除非提交保存选项,则还可以覆盖视图的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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.