1π
The pk
URL is supposed to be part of the URL, so you need to update the urlpatterns
to:
path('add_child/<int:pk>/', views.addChild, name='add_child'),
If you thus visit the URL, you should visit add_child/123/
with 123
the primary key of the parent for which you want to add a child.
Since the primary key of the parent is in the URL, it makes not much sense to keep it in the form. You can rewrite the ChildForm
to:
from django import forms
class ChildForm(forms.ModelForm):
class Meta:
model = Child
fields = ['first_name', 'last_name'] # β no parent
and let the view set the parent when submitting the form:
from django.shortcuts import redirect
def addChild(request, pk):
if request.method == 'POST':
form = ChildForm(request.POST)
if form.is_valid():
form.instance.parent_id = pk
form.save()
return redirect('name-of-some-view')
else:
form = ChildForm(initial={'parent' :parent})
# β¦
Note: In case of a successful POST request, you should make a
redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: Functions are normally written in snake_case, not PascalCase, therefore it is
advisable to rename your function toadd_child
, not.addChild