pythonflaskduplicatesflash-message

Python Flask - Duplicate Flash Messages


I'm having a problem with get_flashed_messages() returning two flash messages.

I have an html form that updates the row values of a table when submitted. Here is the flash message I have set for it:

@main.route("/update", methods=['GET', 'POST'])
def update():
    if request.method == 'POST':
        my_data = FundingSource.query.get(request.form.get('id'))

        my_data.complete = request.form['complete']
        my_data.guidance_tracker = request.form['guidance_tracker']
        my_data.department = request.form['department']
        my_data.agency = request.form['agency']
        my_data.funding_source = request.form['funding_source']

        db.session.commit()
        flash("Funding Source Updated Successfully")

        return redirect(url_for('main.g_master'))

Here is get_flashed_messages() in my template file:

{% with messages = get_flashed_messages() %}
                {% if messages %}
                    {% for message in messages %}
                        <div class="alert alert-success alert-dismissible" role="alert">
                            <button type="button" class="close" data-dismiss="alert" aria- 
                                    label="close">
                                <span aria-hidden="true">x</span>
                            </button>
                            {{message}}
                        </div>
                    {% endfor %}
                {% endif %}
{% endwith %}

When I run my Flask application, this is the output I get after I press "update" on the form:

127.0.0.1 - - [23/Dec/2021 02:09:02] "POST /update HTTP/1.1" 302 -
127.0.0.1 - - [23/Dec/2021 02:09:02] "GET /guidanceMaster HTTP/1.1" 200 -
127.0.0.1 - - [23/Dec/2021 02:09:02] "GET /static/main.css HTTP/1.1" 304 -
127.0.0.1 - - [23/Dec/2021 02:09:02] "GET /static/backdrop1.jpg HTTP/1.1" 304 -

How can I stop from getting two identical flash messages?


Solution

  • Solved the problem! I was calling get_flashed_messages() in one of my layout template files, and that template file was being inherited in one of my other template files, hence the duplicate messages.

    For anyone else trying to resolve the issue, check if your calling the get_flashed_messages() function elsewhere in your file.