Dynamically adding a form to a Django formset with Ajax -


I want to automatically add a new look into a Django formset using Ajax, so that when the user clicks on a "add" button Does Javascript run a new form on the page (which is part of the formatting)

this

  & lt; H3 & gt; My services & lt; / H3 & gt; How do I use my template:  

{{ServiceFormset.management_form}} {% form for FormFormset.forms%} & lt; Div class = 'table' & gt; & Lt; Table class = 'noirr' & gt; {{Form.as_table}} & lt; / Table & gt; & Lt; / Div & gt; {% Endfor%} & lt; Input type = "button" value = "add more" id = "add_more" & gt; & Lt; Script & gt; $ ('# Add_more') Click (function () {clone more ('div.table: last', 'service');}); & Lt; / Script & gt;

In a JavaScript file:

  function clone more (selector, type) {var newElement = $ (selector) .clone (true); Var total = $ ('# id_' + type + '-TOTAL_FORMS'). Val (); ('-' + (total -1) + '-', '-' (': input') each (function () {var name = $ (this) .attr ('name'). ('' Name '(Name' id ': id}) val (' ') removed et (' check ');}); per (' - '+ (total -1) +' - ',' - '+ ( '' '' Total + '-'); $ (this) .attr ('for', newFor);}); Total ++; $ ('# Id_' + type + '-TOTAL_FORMS') Val (total); $ (selector) .after (newElement);}  

What this does:

accept more cloning It does selector as the first argument, and what should selector do as the second one of the type formset, pass it In this case, let me pass it to div.table: last so that the last table with the jQuery table class appears : Part of the last is important because the selector is also used to determine how the new form will be inserted after which the more you want, the more you want the rest of the form Lastly, want to do this type the argument is this That we can update the management_form field, especially TOTAL_FORMS , as well as the actual form fields. If you have filled out a form, then say, Customer model will be the ID of the id_clients-TOTAL_FORMS and id_clients-INITIAL_FORMS in the Management field Form fields beginning with form code 0 will be in the format of N with id_clients-n-fieldname . Therefore, the clone more function with the type argument currently looks at how many forms, and with each input name and id, replace all the field names / ids with each input and label Goes through the medium such as id_clients- (N) -name to id_clients- (N + 1) -name and so on. After it finishes, it updates the TOTAL_FORMS field to reflect the new form and adds it to the end of the set.

This function is especially useful to me because the way the setup is, it allows me to use it in full application to provide more form in the app, and as long as I have it named format I do not pass, by then I do not have to create a hidden "template" form in which the form is kept. Hope it helps.


Comments