Skip to content

Instantly share code, notes, and snippets.

@ghickman
Created June 11, 2011 11:19
Show Gist options
  • Save ghickman/1020463 to your computer and use it in GitHub Desktop.
Save ghickman/1020463 to your computer and use it in GitHub Desktop.
Add an inline Django form to the formset without reloading the page.
function add_inline_form(prefix) {
var count = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val(), 10);
var last_form = $('.' + prefix + ':last');
var new_form = last_form.clone(false).html(last_form.html().replace(
new RegExp(prefix + '-\\\\d-', 'g'), prefix + '-' + count + '-'));
new_form.find('input[type="text"], textarea').each(function () {
$(this).val('');
});
new_form.hide().insertAfter(last_form).slideDown(300);
// Update the total form count
$('#id_' + prefix + '-TOTAL_FORMS').val(count + 1);
// re-initialise triggers
return false;
}
var regex = /(?:inline\-form) ([\\w\-]*) (?:add|existing)/;
$('.add-inline').each(function () {
var match = regex.exec($(this).closest('.body').find('.inline-form').attr('class'));
if (match && match.length > 1) {
$(this).click(function () {
return add_inline_form(match[1]);
});
}
});
<div class="body">
{{ prefix_formset.management_form }}
{{ prefix_formset.non_form_errors }}
{% for form in prefix_formset.forms %}
<div class="inline-form prefix">
{{ form|as_uni_form }}
</div>
{% endfor %}
<div class="new-inline">
<input type="button" class="add-inline" value="Add another form" />
</div>
</div>
@AminsabernezhadGit
Copy link

as

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment