[Answered ]-Django – submit multiple forms in a view

2👍

Two errors are present. If I understand right, you’re expecting the data from a Person instance and the data from its accompanying PersonInfo instance to print on the same line. However, you’re trying to achieve this by using chain, which is not joining the querysets based on their relationship, but rather concatenating them blindly.

So if Person.objects.all() returns a queryset which contains the following data

id  person   address   phone_number    hobbies   
1      1         a         a             a
2      2         5         5             5

and PersonInfo.objects.all() returns a queryset which contains

id   Name 
1    aaa      
2    aa       

chain combines them as

id  person  name   address   phone_number    hobbies
1           aaa
2           aa
1      1             a           a             a
2      2             5           5             5

Instead, you should utilize the relationship between the models. If you pass only the Person queryset as context to your template, you could write

{% for p in persons %}
    <tr>
        <td>{{ p.person.name }}</td>
        <td>{{ p.address }}</td>
        <td>{{ p.phone_number }}</td>
        <td>{{ p.hobbies }}</td>
    </tr>
{% endfor %}

Additionally you are setting the Personinfo related instance incorrectly when you save your forms. By using b.ForeignkeytoA you are creating a new variable as a member of the object b called ForeignkeytoA, which has nothing to do with the Personinfo relationship. To set the related Personinfo, you should reference the name of the foreign key field, person. To correct this, that segment should be

# ...
b = form.save(commit = False)
b.person = a
b.save()
# ...

Leave a comment