2👍
A ForeignKey is simply a pointer to specific row in another table. What your Person
model says is “Every person has one or two telephones. Each telephone is stored in another table called ‘Phone’.”
So, unless you are doing something sophisticated, your Person
form is asking you to associate two existing Phones for your new Person.
(editing to respond to your comment).
If what you want to do is to have multiple phones, then what you need is a formset
The first thing you need to do is to change which table points at which: instead of the person pointing to a phone, the phone should point to a person. So, for example, add belongs_to = models.ForeignKey(Person)
to your phone model declaration.
The next step is to actually ask for the phones in your view. Here is where formsets come in. In your views, create a formset:
#in views.py
from django.forms.formsets import formset_factory
PhoneFormset = formset_factory(PhoneForm, extras = 1)
if request.method == 'POST':
phone_formset = PhoneFormset(request.POST, prefix = 'phone_formset')
person_form = PersonForm(request.POST, prefix='person_form')
# validate your forms, etc
else:
person_form = PersonForm()
phone_formset = PhoneFormset(prefix = 'phone_formset')
Add phone_formset
to the dictionary passed to your template, end render it as so:
# in your template
<form>
{{person_form.as_p}}
{% for phone_form in phone_formset %}
{{phone_form.as_table}}
{% endfor %}
</form>
The last thing you need to do is to set each phone’s belongs_to
field to the Person who submitted the form. You will have to do this in your view: maybe save your person before saving your phones, get their pk, set the Phone’s foreign key and then save it.