简体   繁体   English

使用WTForms FieldList

[英]Working with WTForms FieldList

I use WTForms with Flask via the Flask.WTF extension. 我通过Flask.WTF扩展使用带有Flask的WTForms。 This question isn't Flask-specific, though. 不过,这个问题不是Flask特有的。

WTForms includes a FieldList field for lists of fields . WTForms包括字段列表的FieldList字段 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 . Deform这样的其他框架也支持Ajax Is there a similar framework available for WTForms? WTForms是否有类似的框架?

I used something like this with my FieldList/FormField to allow adding more entries: 我在FieldList / FormField中使用了类似的东西来添加更多条目:

$(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 mostly borrowed from answer to Dynamically adding a form to a Django formset with Ajax .) (代码主要是从使用Ajax动态添加表单到Django formset的答案中借用的。)

From your description, I can't see why Ajax is particularly needed, though of course you do need JavaScript logic to add/remove rows. 从您的描述中,我看不出为什么特别需要Ajax,当然您确实需要JavaScript逻辑来添加/删除行。 I've implemented this functionality using WTForms, but with with no special support from WTForms itself; 我已经使用WTForms实现了这个功能,但没有来自WTForms本身的特殊支持; you just need to ensure that when you create client-side widgets, you do this using field names that WTForms will parse correctly into the server-side list. 您只需要确保在创建客户端小部件时,使用WTForms将正确解析到服务器端列表中的字段名称来执行此操作。 You can clone an existing row using client-side JavaScript to add rows, so that the rendering of a row is consistent across rows generated server-side and rows created client-side. 您可以使用客户端JavaScript克隆现有行以添加行,以便在服务器端生成的行和客户端创建的行之间呈现行的一致性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM