I want to add or remove new WTForm input fields with button, using Jquery, just like here http://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery/comment-page-1 but using my form-fields.
my form:
class EditBook(Form):
title = TextField('title', validators = [Required()])
authors = FieldList(TextField())
problem is that I can't just append for example
$(InputsWrapper).append("{{form.authors(size=20)}}");
it just prints this text.
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())
来源:https://stackoverflow.com/questions/23915132/how-can-i-dynamically-add-a-wtforms-textfield-to-a-fieldlist-using-jquery