0

i am new to django and jquery and trying do develop first application. My problem is django generated modelformset field values are going blank (reset to default) when I add another (second and subsequent) modelformset to div via ajax call.

'.additem` is class for button calling django view function which is generating formset. I believe it is something related to binding values to form resetting form values to default. I tried adding event.preventdefault() but no success.

jQuery code with ajax call is as follows:

$(document).on("click", '.additem', function(event) {
    $.ajax({
        url: 'additem',
    data: { additem: 1},
    type: 'get',                   
    success: function(response){
    event.preventDefault();
            console.log(response);
            var form_idx = parseInt($("#id_detail-TOTAL_FORMS").val());
            modified_response = response.replace(/ detail - 0 / g, "detail-" + form_idx);
    $('#detail').html($('#detail').html() + modified_response); 
    $("#id_detail-TOTAL_FORMS").val(parseInt(form_idx) + 1);
        },
    failure: function(data) {
            alert('Got an error dude');
        }
    });
});

# django view code

    if request.method == 'GET' and 'additem' in request.GET:
        f = self.detailform_class
        fd = f._meta.fields

        formsetclass = modelformset_factory(detailmodel_class, form= f, fields= fd,extra =1, can_delete=True  )
        formset = formsetclass(queryset=detailmodel_class.objects.none(), prefix='detail',initial =[{self.related_field:pk}])
        html = render_to_string('mm/formset4.html', {'sub_form': formset})
        return HttpResponse(html)   
Ravi
  • 1
  • 3
  • I could resolve the issue as I replace html()+response with .append(response). I think my question was not clear. Next time will try in a better way. – Ravi Aug 11 '18 at 10:08
  • I am unable to close the question. pl help me how to do it. – Ravi Aug 11 '18 at 10:11

0 Answers0