Created
January 19, 2016 14:04
-
-
Save doobeh/5d0f965502b86fee80fe to your computer and use it in GitHub Desktop.
More complete example of FieldList with FormField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form method="post" action=""> | |
{{ form.name}} | |
{{ form.hidden_tag() }} | |
<br/> | |
{% for entry in form.hours %} | |
{{ loop.index0|dow }} | |
{{ entry() }} | |
{% endfor %} | |
<input type="submit"/> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, render_template | |
from flask_wtf import Form | |
from wtforms import StringField, FormField, FieldList, HiddenField | |
import calendar | |
app = Flask(__name__) | |
app.secret_key = 'SCRATCH' | |
def dow_name(dow): | |
return calendar.day_name[dow] | |
app.jinja_env.filters['dow'] = dow_name | |
class TimeForm(Form): | |
opening = StringField('Opening Hour') | |
closing = StringField('Closing Hour') | |
day = HiddenField('Day') | |
class BusinessForm(Form): | |
name = StringField('Business Name') | |
hours = FieldList(FormField(TimeForm), min_entries=7, max_entries=7) | |
@app.route('/', methods=['post','get']) | |
def home(): | |
form = BusinessForm() | |
if form.validate_on_submit(): | |
results = [] | |
for idx, data in enumerate(form.hours.data): | |
results.append('{day}: [{open}]:[{close}]'.format( | |
day=calendar.day_name[idx], | |
open=data["opening"], | |
close=data["closing"], | |
) | |
) | |
return render_template('results.html', results=results) | |
print(form.errors) | |
return render_template('home.html', form=form) | |
if __name__ == '__main__': | |
app.run(debug=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ul> | |
{% for line in results %} | |
<li>{{ line }}</li> | |
{% endfor %} | |
</ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think it uses good practices because Form does not contains any CSRF token.