Dynamically adding a form to a Django formset with

2018-12-31 06:21发布

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 of the formset) to the page.

标签: ajax django
15条回答
不再属于我。
2楼-- · 2018-12-31 07:05

Another cloneMore version, which allows for selective sanitization of fields. Use it when you need to prevent several fields from being erased.

$('table tr.add-row a').click(function() {
    toSanitize = new Array('id', 'product', 'price', 'type', 'valid_from', 'valid_until');
    cloneMore('div.formtable table tr.form-row:last', 'form', toSanitize);
});

function cloneMore(selector, type, sanitize) {
    var newElement = $(selector).clone(true);
    var total = $('#id_' + type + '-TOTAL_FORMS').val();
    newElement.find(':input').each(function() {
        var namePure = $(this).attr('name').replace(type + '-' + (total-1) + '-', '');
        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
        var id = 'id_' + name;
        $(this).attr({'name': name, 'id': id}).removeAttr('checked');

        if ($.inArray(namePure, sanitize) != -1) {
            $(this).val('');
        }

    });
    newElement.find('label').each(function() {
        var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
        $(this).attr('for', newFor);
    });
    total++;
    $('#id_' + type + '-TOTAL_FORMS').val(total);
    $(selector).after(newElement);
}
查看更多
人间绝色
3楼-- · 2018-12-31 07:05

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 %}
    <fieldset class="languages-{{forloop.counter0 }} {% if spokenLanguageFormset.initial_forms|length < forloop.counter and forloop.counter != 1 %}hidden-form{% endif %}">

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();
        };
    };
}
查看更多
明月照影归
4楼-- · 2018-12-31 07:06

Check out the following solutions to dynamic django forms:

http://code.google.com/p/django-dynamic-formset/

https://github.com/javisantana/django-dinamyc-form/tree/master/frm

They both make use of jQuery and are django-specific. The first seems a bit more polished and offers a download that comes w/demos which are excellent.

查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 07:09

One option would be to create a formset with every possible form, but initially set the unrequired forms to hidden - ie, display: none;. When it's necessary to display a form, set it's css display to block or whatever is appropriate.

Without know more details of what your "Ajax" is doing, it's hard to give a more detailed response.

查看更多
君临天下
6楼-- · 2018-12-31 07:13

For the coders out there who are hunting resources to understand the above solutions a little better:

Django Dynamic Formsets

After reading the above link, the Django documentation and previous solutions should make a lot more sense.

Django Formset Documentation

As a quick summary of what I was getting confused by: The Management Form contains an overview of the forms within. You must keep that information accurate in order for Django to be aware of the forms you add. (Community, please give me suggestions if some of my wording is off here. Im new to Django.)

查看更多
几人难应
7楼-- · 2018-12-31 07:14

I think this is a much better solution.

How would you make a dynamic formset in Django?

Does things clone doesn't:

  • Add form when no initial forms exists
  • Handles javascript in the form better, for example django-ckeditor
  • Keep initial data
查看更多
登录 后发表回答