Bayko
Bayko

Reputation: 1434

Django submitting two forms with a foreign key

I am trying to submit two forms in one template. With one model key being the foreign key for the other model. The foreign key will be set after the POST has been done.

class CustomerSystem(models.Model):
    ---Some fields---

class MN(models.Model):
    --some fields--
    customer_system_serial_number = models.ForeignKey(CustomerSystem, on_delete= models.CASCADE)

This is how my models.py looks like

The template file is a standard template with 'form' variable

In forms.py I have excluded the customer_system_serial_number from the MN model.

This is what I am attempting in views

@login_required
def add_customers(request):
    if request.method == 'POST':
        form_cs = CustomerSystemForm(request.POST, prefix='cs')
        form_mn = MNForm(request.POST, prefix='mn')
        if form_cs.is_valid() and form_mn.is_valid():
            model_instance = form_cs.save(commit=False)
            model_instance.save()
            print(model_instance)
            form_mn.customer_system_serial_number = model_instance
            form_mn.save()
            return HttpResponseRedirect('/database/customers')
    else:
        form_cs = CustomerSystemForm(request.POST, prefix='cs')
        form_mn = MNForm(request.POST, prefix='mn')
        return render(request, 'database/customer_system.html', {'form_cs': form_cs, 'form_mn': form_mn})

The error I am getting is the not Integrity error/not null error. I can see that the model_instance is being saved since it prints a valid object. I am trying to do something like how to set foreign key during form completion (python/django) However I am clearly missing something probably very basic. Any help is appreciated

Upvotes: 0

Views: 331

Answers (2)

Chandan Kumar
Chandan Kumar

Reputation: 899

Given answer didn't work for me, need to use FK with . dot not equal = sign.

Working code

model_instance = form_cs.save()
mn_instance = form_mn.save(commit=False)
mn_instance.customer_system_serial_number = model_instance
mn_instance.save()
return HttpResponseRedirect('/database/customers')

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599600

You're doing the commit=False on the wrong form, and you're setting the foreignkey onto the MN form, not the model instance.

        model_instance = form_cs.save()
        mn_instance = form_mn.save(commit=False)
        mn_instance = customer_system_serial_number = model_instance
        mn_instance.save()
        return HttpResponseRedirect('/database/customers')

Upvotes: 1

Related Questions