Last active
July 31, 2021 03:12
-
-
Save rmrfus/8c9bfbcba7fcd50a8031eef44dc9fbf5 to your computer and use it in GitHub Desktop.
WtForms Demo
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="/"> | |
{% 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> |
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
#!/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