本文介绍了与WTForms FieldList中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过Flask.WTF扩展使用WTForms与瓶。这个问题是不是瓶专用,虽然。

I use WTForms with Flask via the Flask.WTF extension. This question isn't Flask-specific, though.

WTForms包括<一个href="http://wtforms.simple$c$cs.com/docs/0.6.1/fields.html#wtforms.fields.FieldList"><$c$c>FieldList字段的字段列表。我想用这个做一个表格,用户可以添加或删除项目。这将需要某种形式的Ajax框架的动态添加窗口小部件,但WTForms文件没有提到这一点。

WTForms includes a FieldList field for lists of fields. I'd like to use this to make a form where users can add or remove items. This will require some sort of Ajax framework to dynamically add widgets, but the WTForms documentation makes no mention of it.

变形其他框架配备了Ajax支持。是否有可用的WTForms一个类似的框架?

Other frameworks like Deform come with Ajax support. Is there a similar framework available for WTForms?

推荐答案

我用这样的事情与我的FieldList中/ FormField允许添加更多的条目:

I used something like this with my FieldList/FormField to allow adding more entries:

$(document).ready(function () {
    $('#add_another_button').click(function () {
        clone_field_list('fieldset:last');
    });
});

function clone_field_list(selector) {
    var new_element = $(selector).clone(true);
    var elem_id = new_element.find(':input')[0].id;
    var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
    new_element.find(':input').each(function() {
        var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + elem_num + '-');
        $(this).attr({'name': id, 'id': id}).val('').removeAttr('checked');
    });
    new_element.find('label').each(function() {
        var new_for = $(this).attr('for').replace('-' + (elem_num - 1) + '-', '-' + elem_num + '-');
        $(this).attr('for', new_for);
    });
    $(selector).after(new_element);
}

删除按钮会更棘手。

Remove buttons would be much trickier.

(code主要来自答案借来Dynamically添加一个表单一个Django表单集与阿贾克斯。)

(Code mostly borrowed from answer to Dynamically adding a form to a Django formset with Ajax.)

这篇关于与WTForms FieldList中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 15:58