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


-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/668f3879-1659-4867-867a-8f56e6996af0%40googlegroups.com.

Reply via email to