Skip to content

Instantly share code, notes, and snippets.

@nenodias
Created March 29, 2022 14:13
Show Gist options
  • Save nenodias/daa52dd2e8ca7a7823ab43231e22c11c to your computer and use it in GitHub Desktop.
Save nenodias/daa52dd2e8ca7a7823ab43231e22c11c to your computer and use it in GitHub Desktop.
Flask WTF FieldList add and remove feature
from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, FormField, FieldList, IntegerField, Form
from wtforms.validators import Optional
from collections import namedtuple
app = Flask(__name__)
app.config['SECRET_KEY'] = 'keepthissecret'
class ProductForm(Form):
title = StringField('Title')
price = IntegerField('Price', validators=[Optional()])
class InventoryForm(FlaskForm):
category_name = StringField('Category Name')
products = FieldList(FormField(ProductForm), min_entries=0)
product = namedtuple('Product', ['title', 'price'])
@app.route('/', methods=['GET', 'POST'])
def index():
data = {
'category_name' : 'Widgets',
'products' : []
}
form_data = request.form or data
print(form_data)
form = InventoryForm(data=form_data)
if form_data.get('add', False):
form.products.append_entry(product('', 0))
remove = form_data.get('remove', None)
if remove is not None:
form.products.entries.pop(int(remove))
if form.validate_on_submit():
if form_data.get('submit') is not None:
print("Doing the post")
print(form.data)
for idx, field in enumerate(form.products):
print("idx:",idx)
print("title:",field.title.data)
print("price:",field.price.data)
return render_template('index.html', form=form)
if __name__ == "__main__":
app.run(host='127.0.0.1',port=8000,debug=True)
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FieldList Example</title>
</head>
<body>
<form method="POST" action="">
{{ form.hidden_tag() }}
{{ form.category_name.label }} {{ form.category_name }}
<br />
{% for nested in form.products %}
{{ nested.label }}{{ nested }}
<button value="{{ loop.index -1 }}" name="remove">remove</button>
<br />
{% endfor %}
<button value="add" name="add">Add</button>
<button value="submit" name="submit">Submit</button>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment