Встроенный Formset с отношением многие ко многим в django CreateView - PullRequest
0 голосов
/ 24 января 2020

Я не могу заставить его работать. У меня есть две модели «Курс» и «Исход». Я хочу сделать форму OutcomeForm в виде встроенной формы в CourseForm.

Мой файл models.py выглядит следующим образом:

class Outcome(models.Model):
# some fields
course_outcome = models.ForeignKey(
    "course.Course", on_delete=models.SET_NULL, blank=True, null=True
)

class Course(models.Model):
# some fields
course_outcome = models.ManyToManyField(
    Outcome, verbose_name=COURSE_SINGULAR + " outcome", blank=True
)

И встроенный набор форм создается следующим образом:

OutcomeFormSet = inlineformset_factory(
    parent_model=Course,
    model=Outcome,
    form=OutcomeForm,
    extra=1,
    can_delete=True,
)

И файл views.py:

class CourseCreateForm(CreateView):
    model = Course
    template_name = "course/course_form.html"
    form_class = CourseForm
    success_url = reverse_lazy("course")

    def get_context_data(self, **kwargs):
        context = super(CourseCreateForm, self).get_context_data(**kwargs)
        if self.request.POST:
            context["outcomes"] = OutcomeFormSet(self.request.POST)
        else:
            context["outcomes"] = OutcomeFormSet()
        return context

    def form_valid(self, form, **kwargs):
        super(CourseCreateForm, self).get_context_data(**kwargs)
        context = self.get_context_data()   
        outcomes = context["outcomes"]
        with transaction.atomic():
            if outcomes.is_valid():
                self.object = form.save()
                outcomes.instance = self.object
                outcomes.save()
                form.instance.course_outcome.set(
                    Outcome.objects.filter(course_outcome=self.object)
                )
                form.save()
        return super().form_valid(form)

Проблема в том, что сохраняются все данные модели Outcome и Course, кроме поля m2m модели курса.

Я застрял в этой точке , Любой указатель в правильном направлении будет высоко оценен.

Заранее спасибо

...