Friday, January 24, 2020

Inline formset for many to many relation

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,

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ef3447dc-b99d-41c7-968a-0e2d15275fee%40googlegroups.com.

No comments:

Post a Comment