Child form instance in Django

As a beginner in a contact list project I could not pass the instance of the contact profiles to the phone list form. When I want to add several phone numbers to a person I need the person's instance to be loaded to the add-phone form.

models.py

class newuser(forms.ModelForm):
    class Meta:
        model= contact_names
        fields='__all__'
        
class newphone(forms.ModelForm):
    class Meta:
        model=contact_phone
        fields=['person','typep','phone']

views.py

def user(request):
    form=newuser()
    if request.method =='POST':
        form=newuser(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return redirect('contacts')
    return render(request,'apptwo/form_page.html',{'form':form})

def addphone(request,pk):
    ps=contact_names.objects.get(id=pk)
    form=newphone(instance=ps)
    if request.method =='POST':
        form=newphone(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return redirect('contacts')
    return render(request,'apptwo/form_page2.html',{'form':form})

forms.py

class newuser(forms.ModelForm):
    class Meta:
        model= contact_names
       
        fields='__all__'
        
class newphone(forms.ModelForm):
    class Meta:
        model=contact_phone
        fields=['person','typep','phone']

It looks like you're trying to create a phone number form that is associated with a specific contact profile. In your addphone view, you are correctly fetching the contact profile from the database using the primary key (pk) passed in through the URL, but in the POST portion of the view, you are creating a new form without passing in the instance of the contact profile that you fetched earlier.

To fix this, you should update the POST portion of the addphone view to use the instance of the contact profile when creating the phone number form:

if request.method =='POST':
form=newphone(request.POST,instance=ps)
if form.is_valid():
    form.save(commit=True)
    return redirect('contacts')

Also, In your form, you should define the foreign key to person and it should be hidden in the form,

class newphone(forms.ModelForm):
person = forms.ModelChoiceField(queryset=contact_names.objects.all(), widget=forms.HiddenInput())
class Meta:
    model=contact_phone
    fields=['person','typep','phone']

This way when you save the form, the person foreign key will be automatically set to the instance of the contact you passed.

Back to Top