Dynamically adding a form to a Django formset with Ajax

后端 未结 15 1927
不思量自难忘°
不思量自难忘° 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条回答
  •  悲&欢浪女
    2020-11-22 03:20

    Because all answers above use jQuery and make some things a bit complex I wrote following script:

    function $(selector, element) {
        if (!element) {
            element = document
        }
        return element.querySelector(selector)
    }
    
    function $$(selector, element) {
        if (!element) {
            element = document
        }
        return element.querySelectorAll(selector)
    }
    
    function hasReachedMaxNum(type, form) {
        var total = parseInt(form.elements[type + "-TOTAL_FORMS"].value);
        var max = parseInt(form.elements[type + "-MAX_NUM_FORMS"].value);
        return total >= max
    }
    
    function cloneMore(element, type, form) {
        var totalElement = form.elements[type + "-TOTAL_FORMS"];
        total = parseInt(totalElement.value);
        newElement = element.cloneNode(true);
        for (var input of $$("input", newElement)) {
            input.name = input.name.replace("-" + (total - 1) + "-", "-" + total + "-");
            input.value = null
        }
        total++;
        element.parentNode.insertBefore(newElement, element.nextSibling);
        totalElement.value = total;
        return newElement
    }
    var addChoiceButton = $("#add-choice");
    addChoiceButton.onclick = function() {
        var choices = $("#choices");
        var createForm = $("#create");
        cloneMore(choices.lastElementChild, "choice_set", createForm);
        if (hasReachedMaxNum("choice_set", createForm)) {
            this.disabled = true
        }
    };
    

    First you should set auto_id to false and so disable the duplication of id and name. Because the input names have to be unique in there form, all identification is done with them and not with id's. You also have to replace the form, type and the container of the formset. (In the example above choices)

提交回复
热议问题