Skip to content

Instantly share code, notes, and snippets.

@mvmthecreator
Created December 6, 2016 02:20
Show Gist options
  • Save mvmthecreator/312660386ca5e2e7d01dfaa4fcbe3cd9 to your computer and use it in GitHub Desktop.
Save mvmthecreator/312660386ca5e2e7d01dfaa4fcbe3cd9 to your computer and use it in GitHub Desktop.
flask wtfroms and jquery
# index.html
{% extends "bootstrap/base.html" %}
{% set counter = 0 %}
{% macro render_field(field, count, _class="form-control") %}
<td>{{ field.label }}</td>
<td>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</td>
{% endmacro %}
{% block content %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$("#listItems").append('{{ render_field| safe, counter }}');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
<button id="add">Click</button>
<div id="listItems">
{% for item in form.contacts %}
{% set counter = counter + 1%}
{% for it in item %}
{{ render_field(it, counter) }}
{% endfor %}
{% endfor %}
</div>
{% endblock %}
# app.py
from flask import Flask, render_template
from flask_wtf import FlaskForm
from flask_bootstrap import Bootstrap
from wtforms import StringField, validators, FieldList, FormField, SubmitField
class ContactForm(FlaskForm):
description = StringField('Description')
phone = StringField('Phone')
class PersonForm(FlaskForm):
username = StringField('Name', [validators.Length(min=4, max=25)])
contacts = FieldList(FormField(ContactForm), min_entries=1)
send = SubmitField('Submit')
app = Flask(__name__)
Bootstrap(app)
app.config['SECRET_KEY'] ='blabla'
app.config['WTF_CSRF_ENABLED'] = False
@app.route('/', methods = ('GET', 'POST'))
def index():
form = PersonForm()
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True, port=5004)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment