It gets inserted via the form.hidden_tag()
. See the chunk of html on the login page below (and note the registration page is basically the same chunk of code):
<body>
{% if current_user.is_authenticated %}
... code to display game once user logs in ...
{% else %}
<img src="../static/assets/divinitypluslogo.png" width="130"></img>
<p>Your addictive web-based MMORPG</p>
<div class="container">
<h2>Login</h2>
<form method="POST" action="">
{{ form.hidden_tag() }}
{{ form.username }}
{{ form.password }}
{{ form.submit }}
</form>
</div>
<form action="/register" method="POST">
<p>Don't have an account? </p><a href="/register">Sign Up!</a>
</form>
{% endif %}
</body>
Where current_user
is the current_user
variable from the flask_login
library. For additional information, the python code that handles this login looks like the following:
...
class LoginForm(FlaskForm):
username = StringField(validators=[InputRequired(), Length(min=3, max=50)], render_kw={"placeholder": "Username"})
password = PasswordField(validators=[InputRequired(), Length(min=4, max=50)], render_kw={"placeholder": "Password"})
submit = SubmitField("Login")
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
... some other pages ...
@app.route("/", methods=["POST", "GET"])
@app.route("/home", methods=["POST", "GET"])
def home():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
# Messages (When adding a date/most recent, make sure to sort by that. For now, ignore time)
messages = History.query.all()
messages = list(reversed(messages))
return render_template("home.html", form=form, current_user=current_user, messages=messages)
...