I'm trying to set up flash message to advise user that register was successful, for instance.

I followed this documentation and a few variants, but still it does not show.

I have also found this questions on SO, that suggests that the issue is with the SERVER_NAME configuration.

This should be very straight forward, so please check my code below.



from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request,     session, url_for
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions
from werkzeug.security import check_password_hash, generate_password_hash

from helpers import apology, login_required, lookup, usd
from inspect import getmembers
from pprint import pprint

# Configure application
app = Flask(__name__)

# this seems to be the only acceptable parameter, otherwise will 404
app.config['SERVER_NAME'] = 'ide50-myname.cs50.io:8080'

@app.route("/register", methods=["GET", "POST"])
def register():
""" Register user """

# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
    if not result:
        return apology("Username already taken", 403)

    if result:
        flash("Register succesful")
        # here I tried with plain redirect, without using url_for, with no luck
        # it will show the message if used with render_template, but that does not work well for the app
        return redirect(url_for('login'))

# User reached route via GET (as by clicking a link or via redirect)
    return render_template("register.html")

In flask, flash messages are stored in the session cookie. The first thing that login does is session.clear(), which destroys the cookie, and with it, the message.

I would never recommend removing the session.clear() for any number of reasons (it's in the supplied code, it could be a security hole, it might not pass check50).

Notice how the staff solution goes right into the app after you register, not asking for login credentials. Also notice that helpers.login_required checks that session['user_id'] is set. login sets it. You could do something similar in register.

  • Well, I will log the user in automatically after register. Sounds like the only decent solution given the resources. Thanks – BernardA Apr 9 '18 at 20:26

I ran into a similar issue with flash() and redirect() too: I was trying to redirect back to /login while displaying a flash error message if the user did not enter a username or wrong password and etc.

In application.py, under @app.route("/login"), I made the following modifications:

    if session["user_id"]:    

This clears the session only if a user is currently logged in, and my flash now work after redirecting. However, I'm not certain if this change causes security issues.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .