Unable to save m2m field in Inline Formset with many to many relation in django CreateView

326 views
Skip to first unread message

Suraj

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

I am unable to make it worked. I have two models "Course" and "Outcome". I want to make OutcomeForm form as inline form in CourseForm.

My models.py file looks as below:


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
)


And inline formset is created as:


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


And views.py file is:

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)


The problem is:

All data of model Outcome and Course is saved except m2m field of Course model.

I am stuck at this point. Any pointer in right direction will be highly useful.

Thanks in advance,


--
Suraj
https://hacksj4u.wordpress.com
https://github.com/SurajDadral


Reply all
Reply to author
Forward
0 new messages