Inline formset for many to many relation

23 views
Skip to first unread message

Suraj

unread,
Jan 24, 2020, 3:10:48 PM1/24/20
to Django users
Hello Everyone,

I want to inline formset for m2m relationship. Related code looks as follows:

models.py
```
class Outcome(models.Model):
    # some fields
   # Foreign key is created to make outcomes inline in course form
   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)
```

forms.py
```
class OutcomeForm(forms.ModelForm):
   # some fields

class CourseForm(forms.ModelForm):
   # some fields including inline outcomes

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)
```

All my data in Outcome and Course models saved successfully except m2m field of course model.
Can anyone please guide me what I am doing wrong here.

Thanks in advance,

Reply all
Reply to author
Forward
0 new messages