How can I dynamically add a WTForms TextField to a FieldList using jQuery?

孤人 提交于 2019-12-03 20:44:39

This answer is based on nsfyn55's explanations (first paragraph).

I had a similar problem. The solution was to use: https://github.com/Rhyzz/repeatable-fields

So, all you have to do is to look at the html snippet that is rendered by WTForms and use it as a 'template' in repeatable-fields plugin (see its docs for details)

Your example conflates text generated server side with text you are appending in the browser using javascript. You will not be able to use the {{ }} syntax which is used by the server side templating engine. During rendering these are expanded and replaced with the HTML that is transmitted across the wire to the client. You will instead need to build the actual DOM elements that these built-in template functions would otherwise generate.

The DOM element you actually want to create looks like this:

<input id="authors-0" name="authors-0" type="text" value="Author Guy"></input>
<input id="authors-1" name="authors-1" type="text" value="Other Guy"></input>

This can then be encoded in a multipart/form-data stream that WTForms can work with. So your actually jQuery stuff needs to create a field looks something like this

$('<input>').attr({
    type: 'text',
    id: 'authors-' + index ,
    name: 'authors-' + index, 
    value: value
}).appendTo('form');

Where the index is the next positional index(this could be stored in a data attribute in a wrapping ul) and value is the value you want to assign to this box if any.

Additionally to get a feel for what FieldList renders you can run the code below from the command line. It will print the actual text that WTForms generates during the rendering process.

from wtforms import Form, TextField, FieldList
from webob.multidict import MultiDict

class TestForm(Form):
    authors = FieldList(TextField())

data_in = {'authors': ['Author Guy', 'Other Guy']}
test_form2 = TestForm(data=MultiDict(data_in))
print("HTML Render: %s" % test_form2.authors())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!