Display an error message/Flash message, without using form validation – HTML and Python

Question:

I am building a movie application. I have set up a movie page with brief details about the movie and 2 button: Watched and Saved, which can save into a users watched list or save for later list.
I have set up my backend so that if a user clicks on the watched or saved button more than once, it should not save the movie to the database table watchedmovies or savedmovies. However i am struggling to display an error message that will be displayed to the user.

I am not using forms – so unable to follow the steps to do form validation.

Below is my backend code for the watched route, where I see if the record exists in my database table, if it does i flash or get a message, saying you have already watched this movie. If its not in my database I flash or get message saying it has been saved into your watched list.

cursor.execute( "SELECT * FROM watchedmovies WHERE username LIKE %s", [username_new] )
    watched_post = cursor.fetchone()
    print(watched_post)
    message = ""
    if watched_post:
        message = "You have already saved this movie to your watched list!"
        flash('You have already saved this movie to your watched list!', 'danger')
        return redirect(url_for('movie', id=id))
    else:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('INSERT INTO watchedmovies VALUES (% s, % s, % s)', (watched_username, id, watched_title))
        mysql.connection.commit()
        flash('This movie has been saved to your watched list!', 'success')
        message = 'This movie has been saved to your watched list!'
    return redirect(url_for('user', id=id, username_new=username_new, current_post=curren
t_post, profile_post=profile_post, watched_post=watched_post, message=message))

HTML code snippet of the watched and saved button. I have tried to put the message but it doesnt work

<div class="message">{{ message }}</div>
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{{ url_for('watched', id=current_post.id, username_new=profile_post.username)}}">Watched</a>
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{{ url_for('save', id=current_post.id, username_new=profile_post.username)}}">Saved</a>
Asked By: Jennifer

||

Answers:

You should use get_flashed_messages() function in the jinja template. check the code below, it should work.

  {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            {% for category, message in messages %}
                <div class=" alert alert-{{category}}" role="alert">
                    {{message}}
                </div>
            {% endfor %}
        {% endif %}
    {% endwith %}
Answered By: Elie Saad
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.