Forms with Flask-WTF — A newbie friendly tutorial

In this short tutorial you will learn how to create a (very!) simple app using Flask-WTF. This includes Python, Flask, HTML — and PyCharm.

Use pip install Flask-WTF in the PyCharm Terminal. After that you go to PyCharm /Preferences /Project /Python Interpreter/+. Search for flask-wtf and install it.

MAIN.PYfrom flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length

app = Flask(__name__)
app.secret_key = "any-string-12345"


class
MyLoginForm(FlaskForm):
username = StringField(label='Username', validators=[DataRequired(), Length(min=2)])
submit = SubmitField(label="Login now")


@app.route("/", methods=["GET", "POST"])
def home():
login_form = MyLoginForm()
name = login_form.username.data
if login_form.validate_on_submit():
return render_template('logged_in.html', name=name)
else:
return render_template('login.html', form=login_form)
if __name__ == '__main__':
app.run(debug=True)
LOGIN.HTML<!DOCTYPE html>
<head>
<title>Login</title>
</head>
<body>
<form method="POST" action="{{ url_for('home') }}">
{{ form.csrf_token }}
<p>{{ form.username.label }}<br>{{ form.username(size=30)}}</p>
<p> {{ form.submit }}</p>
</form>
</body>
</html>
LOGGED_IN.HTML<!DOCTYPE html>
<head>
<title>Logged in</title>
</head>
<body>
<h1>{{name}} is logged in!</h1>
</body>
</html>

Copy the files into PyCharm. The file structure has to be the usual Flask file structure. The login.html and the logged_in.html must be in the templates directory!

After successfully running main.py, click on the Python local host http://127.0.0.1:5000/ in the run window. Then a Browser will open and show the Login.

For more information go to https://flask-wtf.readthedocs.io/en/stable/ and https://pypi.org/project/Flask-WTF/.

--

--

--

Code Newbie learning Python

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Getting Clipboard content from remote Selenium Chrome Nodes

Python Object-Oriented Programming: Polymorphism

from fit6 http://ift.tt/2jwbU3C via alanafalk.jimdo.com

Testing the untestable — the case of the ViewModel delegate

I Purchased Macbook Air M1 and I’m a bit Disappointed

Flutter & Flame: Physic-based collisions

Summer internship — 2021 June

Typical Questions When we need Stack.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
k4th4

k4th4

Code Newbie learning Python

More from Medium

Batch coding: The best scripting for starters

in-Operator and having-Clause

Creating a django app in 5 mins!

Link Multiple Files in Excel