elo80ka / django-dynamic-formset

A jQuery plugin that allows you dynamically add new forms to a rendered django formset.
677 stars 311 forks source link

does not seem to work with file fields #196

Open rikengct opened 2 years ago

rikengct commented 2 years ago

it seems that the code can't handle it if you use file fields in your inline formset i noticed that some javascript is inserted to get the file when you have a file field. but, the ids for this script are not updated in jquery.formset.js (only the for, id, and name attributes of the element are updated). so inserted filefield javascript has the same id as the previous one, which makes both fail. i don't know enough to make the code also account for that. please update :)

nessalc commented 1 year ago

I had this same issue. I have a feeling it had/has something to do with me trying to be "fancy" with the styling on my forms, and I don't know what the "correct" fix would be, but the following appears to work (obviously, the jQuery selector will need to change for your own case):

function updateElementIndex(obj) {
    var form_idx=$("#id_link-TOTAL_FORMS").val();
    obj[0].children[0].children[0].id.match(/\d+/g)[0];
    obj.html(obj.html().replace(/(id|name)=(\"[^\"]*)\d+([^\"]*")/g,"$1=$2"+form_idx+"$3"));
    $("#id_link-TOTAL_FORMS").val(parseInt(form_idx) + 1);
}

Then, add it to the added property of your formset call:

$('.individual-form').formset( {
    added: updateElementIndex,
});