Django formset : Save multiple forms from formset











up vote
0
down vote

favorite












I spent several days in order to add dynamically forms to formset and I find a way to do that. But I have a little issue with forms saving because it just saves the first form and not all forms from formset.



This is my formset :



DocumentFormSets = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4)


This is my template :



<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSet.management_form }}
<div id="form_set">
{% for form in DocumentFormSet.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>


This is my JS part :



$('#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);
});


And this is my views.py file :



class PublicationCreateView(EdqmCreateView):
""" Create publication with document form through formsets """
model = Publication
template_name = 'publication/publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
context['DocumentFormSets'] = DocumentFormSets(self.request.POST or None, self.request.FILES or None, prefix='doc')
return context

def form_valid(self, form):
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid() and formsets.is_valid():
self.object = form.save()
for document in formsets:
self.object = document.save()
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)


But I get this issue :




save() prohibited to prevent data loss due to unsaved related object
'publication'.




How I can save my forms from formsets ?



Thank you !










share|improve this question
























  • to make things easier to read, you should use a plural for your formset. But why are you assigning something to document and saving document inside the for loop if document is your formset?
    – dirkgroten
    16 hours ago










  • Also on which line exactly do you get the error? And show us how you construct the formset (your get_context_data)
    – dirkgroten
    16 hours ago












  • @dirkgroten It's the first time I use formsets, so some things are a bit unclear yet. I added get_context_data in my question. The issue is on line : self.object = form.save()
    – Ducky
    16 hours ago










  • is DocumentFormset created using an inlineformset_factory?
    – dirkgroten
    16 hours ago










  • Yes exactly ! I edited my code in order to show you missing elements.
    – Ducky
    16 hours ago















up vote
0
down vote

favorite












I spent several days in order to add dynamically forms to formset and I find a way to do that. But I have a little issue with forms saving because it just saves the first form and not all forms from formset.



This is my formset :



DocumentFormSets = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4)


This is my template :



<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSet.management_form }}
<div id="form_set">
{% for form in DocumentFormSet.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>


This is my JS part :



$('#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);
});


And this is my views.py file :



class PublicationCreateView(EdqmCreateView):
""" Create publication with document form through formsets """
model = Publication
template_name = 'publication/publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
context['DocumentFormSets'] = DocumentFormSets(self.request.POST or None, self.request.FILES or None, prefix='doc')
return context

def form_valid(self, form):
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid() and formsets.is_valid():
self.object = form.save()
for document in formsets:
self.object = document.save()
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)


But I get this issue :




save() prohibited to prevent data loss due to unsaved related object
'publication'.




How I can save my forms from formsets ?



Thank you !










share|improve this question
























  • to make things easier to read, you should use a plural for your formset. But why are you assigning something to document and saving document inside the for loop if document is your formset?
    – dirkgroten
    16 hours ago










  • Also on which line exactly do you get the error? And show us how you construct the formset (your get_context_data)
    – dirkgroten
    16 hours ago












  • @dirkgroten It's the first time I use formsets, so some things are a bit unclear yet. I added get_context_data in my question. The issue is on line : self.object = form.save()
    – Ducky
    16 hours ago










  • is DocumentFormset created using an inlineformset_factory?
    – dirkgroten
    16 hours ago










  • Yes exactly ! I edited my code in order to show you missing elements.
    – Ducky
    16 hours ago













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I spent several days in order to add dynamically forms to formset and I find a way to do that. But I have a little issue with forms saving because it just saves the first form and not all forms from formset.



This is my formset :



DocumentFormSets = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4)


This is my template :



<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSet.management_form }}
<div id="form_set">
{% for form in DocumentFormSet.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>


This is my JS part :



$('#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);
});


And this is my views.py file :



class PublicationCreateView(EdqmCreateView):
""" Create publication with document form through formsets """
model = Publication
template_name = 'publication/publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
context['DocumentFormSets'] = DocumentFormSets(self.request.POST or None, self.request.FILES or None, prefix='doc')
return context

def form_valid(self, form):
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid() and formsets.is_valid():
self.object = form.save()
for document in formsets:
self.object = document.save()
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)


But I get this issue :




save() prohibited to prevent data loss due to unsaved related object
'publication'.




How I can save my forms from formsets ?



Thank you !










share|improve this question















I spent several days in order to add dynamically forms to formset and I find a way to do that. But I have a little issue with forms saving because it just saves the first form and not all forms from formset.



This is my formset :



DocumentFormSets = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4)


This is my template :



<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSet.management_form }}
<div id="form_set">
{% for form in DocumentFormSet.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSet.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>


This is my JS part :



$('#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);
});


And this is my views.py file :



class PublicationCreateView(EdqmCreateView):
""" Create publication with document form through formsets """
model = Publication
template_name = 'publication/publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
context['DocumentFormSets'] = DocumentFormSets(self.request.POST or None, self.request.FILES or None, prefix='doc')
return context

def form_valid(self, form):
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid() and formsets.is_valid():
self.object = form.save()
for document in formsets:
self.object = document.save()
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)


But I get this issue :




save() prohibited to prevent data loss due to unsaved related object
'publication'.




How I can save my forms from formsets ?



Thank you !







django django-forms formset






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 15 hours ago

























asked 16 hours ago









Ducky

2,48511552




2,48511552












  • to make things easier to read, you should use a plural for your formset. But why are you assigning something to document and saving document inside the for loop if document is your formset?
    – dirkgroten
    16 hours ago










  • Also on which line exactly do you get the error? And show us how you construct the formset (your get_context_data)
    – dirkgroten
    16 hours ago












  • @dirkgroten It's the first time I use formsets, so some things are a bit unclear yet. I added get_context_data in my question. The issue is on line : self.object = form.save()
    – Ducky
    16 hours ago










  • is DocumentFormset created using an inlineformset_factory?
    – dirkgroten
    16 hours ago










  • Yes exactly ! I edited my code in order to show you missing elements.
    – Ducky
    16 hours ago


















  • to make things easier to read, you should use a plural for your formset. But why are you assigning something to document and saving document inside the for loop if document is your formset?
    – dirkgroten
    16 hours ago










  • Also on which line exactly do you get the error? And show us how you construct the formset (your get_context_data)
    – dirkgroten
    16 hours ago












  • @dirkgroten It's the first time I use formsets, so some things are a bit unclear yet. I added get_context_data in my question. The issue is on line : self.object = form.save()
    – Ducky
    16 hours ago










  • is DocumentFormset created using an inlineformset_factory?
    – dirkgroten
    16 hours ago










  • Yes exactly ! I edited my code in order to show you missing elements.
    – Ducky
    16 hours ago
















to make things easier to read, you should use a plural for your formset. But why are you assigning something to document and saving document inside the for loop if document is your formset?
– dirkgroten
16 hours ago




to make things easier to read, you should use a plural for your formset. But why are you assigning something to document and saving document inside the for loop if document is your formset?
– dirkgroten
16 hours ago












Also on which line exactly do you get the error? And show us how you construct the formset (your get_context_data)
– dirkgroten
16 hours ago






Also on which line exactly do you get the error? And show us how you construct the formset (your get_context_data)
– dirkgroten
16 hours ago














@dirkgroten It's the first time I use formsets, so some things are a bit unclear yet. I added get_context_data in my question. The issue is on line : self.object = form.save()
– Ducky
16 hours ago




@dirkgroten It's the first time I use formsets, so some things are a bit unclear yet. I added get_context_data in my question. The issue is on line : self.object = form.save()
– Ducky
16 hours ago












is DocumentFormset created using an inlineformset_factory?
– dirkgroten
16 hours ago




is DocumentFormset created using an inlineformset_factory?
– dirkgroten
16 hours ago












Yes exactly ! I edited my code in order to show you missing elements.
– Ducky
16 hours ago




Yes exactly ! I edited my code in order to show you missing elements.
– Ducky
16 hours ago

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265969%2fdjango-formset-save-multiple-forms-from-formset%23new-answer', 'question_page');
}
);

Post as a guest





































active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265969%2fdjango-formset-save-multiple-forms-from-formset%23new-answer', 'question_page');
}
);

Post as a guest




















































































Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

Can I use Tabulator js library in my java Spring + Thymeleaf project?