Django - formset working with multiple forms

Viewed 16

I have three different models illustrated as below and I want to be able to edit three different forms in formset.

models.py

class Parent(models.Model):
    parent_name = models.CharField(max_length=20)

class Child(models.Model):
    child_name = models.CharField(max_length=20)
    parent = models.ForeignKey("Parent",on_delete=models.PROTECT)
    birth_place = models.OneToOneField("BirthPlace", on_delete=models.PROTECT)

class BirthPlace(models.Model):
    place_name = models.CharField(max_length=20)





forms.py

ChildrenFormset = inlineformset_factory(Parent, Child, fields='__all__', extra=0)

So far, I have managed to create a formset where I can work with Parent and Child. Also, in html, I have written some javascript to add a child form dynamically.

Now the problem is embedding form for BirtPlace. I have tried the below:

def add_fields(self, form, index):
    super(ChildrenFormset, self).add_fields(form, index)

    form.initial['birth_place_name']=form.instance.birthplace.place_name

However, it throws RelatedObjectDoesNotExist.

Can you please help? Thanks

0 Answers
Related