I'm a newbie to Django and I'm trying to save a single Model Form twice in my views.py since I want to create two distinct rows in the DB. I am able to save the forms and create two rows in the DB, but unfortunately the values from the second form get saved in both my rows. I want to save two distinct rows for the same Model on clicking the submit button once.
I have gone through the posts - django submit two different forms with one submit button and Django: saving multiple modelforms simultaneously (complex case) , but it did not answer my query, since I want to save the SAME Model Form twice.
Following is my function for saving the Form:
@csrf_protect
@login_required
@never_cache
def testQuotaReq(request):
form1 = quotaRequestForm(request.POST or None)
form2 = quotaRequestForm(request.POST or None)
if form1.is_valid() and form2.is_valid():
form1.process()
save1 = form1.save(commit=True)
save1.save()
form2.process()
save2 = form2.save(commit=True)
save2.save()
return HttpResponse("Form1 Form2 saved")
#else:
# return HttpResponse('Thanks for your request! Your request id is: %d .' % (save1.pk) )
else:
form1 = quotaRequestForm()
form2 = quotaRequestForm()
return render_to_response('quotaRequest.html',
locals(),
context_instance=RequestContext(request))
This above piece of code creates the following rows in the table (simplified to highlight issue):
Id Descr Val CPU RAM Inst
76 testing 18 180 18432 18
75 testing 18 180 18432 18
74 testing 11 110 11264 11
73 testing 11 110 11264 11
Over here, the values received from HTML for row 75 and 76 are different. Similarly for 73 and 74. Am I missing something ? Appreciate your help!
Edit:
HTML Code:
<form method='POST' action='' id="formSubmit"> {% csrf_token %}
<div class="form1">
{{ form1.as_p }}
</div>
<div class="form2">
{{ form2.as_p }}
</div>
<a class="btn btn-info" href="/quotaRequest">Cancel Request</a>
<button type="submit" class="btn btn-info"><b>Submit Request</b></button>
</form>
Also, I edited the function in views.py as below, but I'm still not able to add two distinct rows in the DB for the same modelForm. I am unclear how to use the prefix tag. Help appreciated!
@csrf_protect
@login_required
@never_cache
def testQuotaReq(request):
form1 = quotaRequestForm(request.POST or None, prefix="form-1")
form2 = quotaRequestForm(request.POST or None, prefix="form-2")
if form1.is_valid() and form2.is_valid():
form1.process()
save1 = form1.save(commit=True)
save1.save()
form2.process()
save2 = form2.save(commit=True)
save2.save()
return HttpResponse("Form1 Form2 saved")
# else:
# form1 = quotaRequestForm()
# form2 = quotaRequestForm()
return render_to_response('quotaRequest.html',locals(), context_instance=RequestContext(request))