So, I set the following codes for the sample, followed by a built-in set of forms of its foreign key, a detail of the sample. I also added a dynamic function to it so that you can add multiple lines for a set of forms through jQuery. I got the jQuery section from http://stackoverflow.com/questions/501719/dynamically-adding-a-form-to-a-django-formset-with-ajax . I tried both implementations, but it seems to have the same result. I am wondering if I did something wrong in this view.
views.py
def project_detail (request, project_id):
project = Project.objects.get(id = project_id)
sample_form = SampleForm(request.POST or None, request.FILES or None, instance = project)
SampleInlineFormSet = inlineformset_factory(Sample, SampleDetail, form=SampleDetailForm, extra=1, can_delete = False)
formset = SampleInlineFormSet(request.POST or None, request.FILES or None, prefix="nested")
if request.method == "POST":
if 'sampleform' in request.POST:
if sample_form.is_valid() and formset.is_valid():
sample_temp = sample_form.save()
sample = Sample.objects.get(pk = sample_temp.pk)
objects = formset.save(commit=False)
for object in objects:
object.sample = sample
object.save()
messages.success(request, "Sucessfully Created New Sample Log" )
return HttpResponseRedirect(reverse('projstatus:project_detail', args=(project_id,)))
context = {'project' : project, "sample_form":sample_form, 'formset' : formset}
return render(request, 'projstatus/detail.html', context)
forms.py
<form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{% crispy sample_form %}
<div id="form_set">
{{ formset.management_form }}
{% for form in formset.forms %}
<table class='no_error'>
{{ form.as_table }}
</table>
{% endfor %}
</div>
<input type="button" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
{{ formset.empty_form.as_table }}
</table>
</div>
<script>
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
<button type='submit' class='save btn btn-default' name = 'sampleform'>Save</button>
</form>
However, I have this problem that only the first instance of the form is always saved. no matter how much I invest in dynamically. Can someone please help me?
Edit:

POST JQuery ( 2 )

POST, JQuery, extra = 2. ( 2 )
