I would like to be able to add dynamically django forms
in my formset
with Add
button.
I tried to write different things but I don't overcome to get the expected result up to now.
I have a formset
defined in my forms.py file :
AnimalFormSet = inlineformset_factory(Elevage, Animal, form=AnimalForm, extra=1)
Then, I created in my views.py file this function :
class ElevageCreateView(CreateView):
model = Elevage
template_name = 'elevage_form.html'
def get_context_data(self, **kwargs):
context = super(ElevageCreateView, self).get_context_data(**kwargs)
context['AnimalFormSet'] = AnimalFormSet(self.request.POST or None, self.request.FILES or None)
return context
def form_valid(self, form):
context = self.get_context_data()
animal = context['AnimalFormSet']
if animal.is_valid():
self.object = form.save()
animal.instance = self.object
animal.save()
return super(ElevageCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('animal-list')
Finally, I'm trying to write my template file :
<fieldset>
<legend class="title"><span class="name">{% trans 'Animal form' %}</span></legend>
{{ AnimalFormSet.management_form }}
{% for form in AnimalFormSet.forms %}
<div class='table'>
<table class='no_error'>
{{ form.as_table }}
</table>
</div>
{% endfor %}
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<script>
$('#add_more').click(function () {
cloneMore('div.table:last', 'service');
});
</script>
</fieldset>
And I have javascript function :
<script>
function cloneMore(selector, type) {
var newElement = $(selector).clone(true);
var total = $('#id_' + type + '-TOTAL_FORMS').val();
newElement.find(':input').each(function() {
var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
});
newElement.find('label').each(function() {
var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
$(this).attr('for', newFor);
});
total++;
$('#id_' + type + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
}
</script>
I spent lot of time in order to get the expected result but I don't overcome to get it. SO I need your help if you could help me.
I don't want to use another library, but I accept JS
, AJAX
, JQuery
or django
answers !
Thank you by advance
EDIT :
The issue is :
It displays the first form, but when I want to add a second one by clicking on Add button
, it doesn't create the second one.
So I assume my Django part is good, but not the JS part ?