[Answered ]-Set ForeignKey in Django view.py

1👍

You should check if both forms are valid, and after saving the clientForm, you can set the .cust_id of the .instance wraooed in the criminalForm:

from django.shorcuts import redirect

def clientinfo(request):
    clientForm = ClientInfoForm(prefix='client')
    criminalForm = OCCForm(prefix='criminal')
    if request.method == 'POST':
        clientForm = ClientInfoForm(request.POST, prefix='client')
        criminalForm = OCCForm(request.POST, prefix='criminal')
        if clientForm.is_valid() and criminalForm.is_valid():
            client = clientForm.save()
            criminalForm.instance.cust_id = client.pk
            criminalForm.save()
            return redirect('name-of-some-view')

    return render(
        request,
        'clientinfo.html',
        {'form': clientForm, 'occform': OCCForm}
    )

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: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be cust, instead of cust_id.

Leave a comment