Skip to content

Instantly share code, notes, and snippets.

@rmrfus
Last active July 31, 2021 03:12
Show Gist options
  • Save rmrfus/8c9bfbcba7fcd50a8031eef44dc9fbf5 to your computer and use it in GitHub Desktop.
Save rmrfus/8c9bfbcba7fcd50a8031eef44dc9fbf5 to your computer and use it in GitHub Desktop.
WtForms Demo
<form method="POST" action="/">
{% if form.errors %}
<div>
<ul class="errors">
{% for field_name, field_errors in form.errors|dictsort if field_errors %}
{% for error in field_errors %}
<li>{{ form[field_name].label }}: {{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
<div>
<label>{{ form.username.label }}:</label>
{{ form.username() }}
</div>
<div>
<label>{{ form.email.label }}:</label>
{{ form.email() }}
</div>
<div>
<label>{{ form.birthday.label }}:</label>
{{ form.birthday() }}
</div>
<button type=submit>SUBMIT</button>
</form>
#!/usr/bin/env python3
from flask import Flask, request, render_template, url_for, redirect
from wtforms import Form, validators, DateField, StringField
app = Flask(__name__)
class TestForm(Form):
username: str = StringField("Username", [validators.Length(min=4, max=25)])
email: str = StringField("Email", [validators.email()])
birthday: str = DateField("Birthday", format="%m/%d/%Y")
@app.route("/done")
def done():
return "Molodets"
@app.route("/", methods=["GET", "POST"])
def home() -> str:
if request.method != "POST":
return render_template("main.j2", form=TestForm())
form = TestForm(request.form)
if request.method == "POST" and form.validate():
return redirect(url_for("done"))
return render_template("main.j2", form=form)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment