Dynamically adding a form to a Django formset with Ajax

后端 未结 15 1903
不思量自难忘°
不思量自难忘° 2020-11-22 03:09

I want to automatically add new forms to a Django formset using Ajax, so that when the user clicks an \"add\" button it runs JavaScript that adds a new form (which is part o

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:20

    Yea I'd also recommend just rendering them out in the html if you have a finite number of entries. (If you don't you'll have to user another method).

    You can hide them like this:

    {% for form in spokenLanguageFormset %}
        

    Then the js is really simple:

    addItem: function(e){
        e.preventDefault();
        var maxForms = parseInt($(this).closest("fieldset").find("[name*='MAX_NUM_FORMS']").val(), 10);
        var initialForms = parseInt($(this).closest("fieldset").find("[name*='INITIAL_FORMS']").val(), 10);
        // check if we can add
        if (initialForms < maxForms) {
            $(this).closest("fieldset").find("fieldset:hidden").first().show();
            if ($(this).closest("fieldset").find("fieldset:visible").length == maxForms ){
                // here I'm just hiding my 'add' link
                $(this).closest(".control-group").hide();
            };
        };
    }
    

提交回复
热议问题