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

Audio Steganography using Phase Encoding

1st Project Building a CLI with Ruby

Recipe OSS: How to restore archive or cold archive objects? (Alibaba Cloud)

How to estimate lift-and-shift costs and project Day-2 cloud expenses

Which Data Migration Tools to use when switching CRM platforms

TryHackMe: Linux Fundamentals Part 3 Walkthrough

How Work Is Really Done at ABOUT YOU Tech

This is how I write A BINARY CODE FOR NEGATIVE INTEGERS …

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

Local storage — beginner’s guide

Understanding JavaScript Asynchronous behavior behind the scenes.

Explore the DOM element before using XPath

High Order Array Methods