我正在尝试使用Django ModelForms来让教师安排每周与学生一起上课。但是,每当我从modelform中保存每周课程的新实例时,m2m关系(学生和教师)都不会被保存。
我在Django文档中看得非常广泛,并尝试了一切来解决这个问题,包括在save方法上设置commit = False,然后使用save_m2m方法。没有骰子。
这是我的代码
models.py
class WeeklyClass(models.Model):
status = models.CharField(
max_length=1,
choices=STATUS_CHOICES,
default="A")
students = models.ManyToManyField(
Profile,
limit_choices_to=models.Q(is_teacher=False),
related_name='student_weekly_classes',)
teachers = models.ManyToManyField(
Profile,
limit_choices_to=models.Q(is_teacher=True),
related_name='teacher_weekly_classes',)
class Meta:
verbose_name = 'Class'
verbose_name_plural = 'Classes'
ordering = ["-created"]
forms.py
class WeeklyClassForm(ModelForm):
class Meta:
model = WeeklyClass
fields = [
"status",
"students",
"teachers",
"weekday",
"duration_hours",
"hour",
"minute"]
views.py
@login_required
def new_weekly_class(request):
if request.method == "POST":
form = WeeklyClassForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse(
"weekly_class_list",
kwargs={"username": request.user.username}))
else:
form = WeeklyClassForm()
return render(
request,
"weekly_classes/new_weekly_class.html",
{"form": form})
答案 0 :(得分:0)
form.save()
不直接保存多个实例,因此在保存form.save()之后还调用form.save_m2m()
来保存多个关系。
@login_required
def new_weekly_class(request):
if request.method == "POST":
form = WeeklyClassForm(request.POST, request.FILES)
if form.is_valid():
form.save()
form.save_m2m()
return redirect("weekly_class_list", kwargs={"username": request.user.username})
else:
form = WeeklyClassForm()
template = "weekly_classes/new_weekly_class.html"
context = {"form": form}
return render(request, template, context)
供参考:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method