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/.