flashing message in flask on a bootstrap modal

Viewed 4904

I'm trying to follow the flask documentation. After a successful form submission (a signup form), I flash a message saying 'Signup successful'. However, I'm trying to have this message appear on a bootstrap modal.

Simplified code is...

@app.route('/signup', methods=['GET','POST'])
def signup():
    form = SignupForm()
    if form.validate_on_submit():
        flash('You were successfully signed up')
return render_template('signup.html', form=form)

Now I only need to trigger the modal with the success flash message if form submission is successful. So I had my modal HTML snippet inside the flash message checks.

<HTML code for forms>
<input type='submit' value="Signup" data-toggle="modal" data-target="#myModal">
{% with messages = get_flashed_messages() %}
{% if messages %}
    <ul class=flashes>
    {% for message in messages %}
        <div class="modal fade" id="myModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        {{ message }}
                    </div>
                </div>
            </div>
        </div>
    {% endfor %}
    </ul>
{% endif %}
{% endwith %}

This doesn't trigger the modal at all. Any thoughts on how I might get this to work?

2 Answers

This is an old question (over 5years) but someone may still stumble on this in the future just as I did now.

The previous answer works great if you need not separate script from HTML, if you need to you may do this:

  1. In the HTML file: Add an id to the area that only gets rendered when messages are available. In my case, I added id=flashes
  2. In JS file: Rely on the .length property of JQuery to show the modal only when the message(s) area gets rendered.

HTML

  <!--=== Modal ===-->
  <div class="modal fade" id="modalId" tabindex="-1" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true">
    <div class="modal-dialog modal-sm" role="document">
      <div class="modal-content">
        <div class="modal-body p-2" id="flashes">
          {% with messages = get_flashed_messages() %}
          {% if messages %}
          <ul class="text-center">
            {% for message in messages %}
            <li>{{ message }}</li>
            {% endfor %}
          </ul>
          {% endif %}
          {% endwith %}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Dimiss</button>
        </div>
      </div>
    </div>
  </div>
  <!--=== Add this script after JQ ===--->
  <script src="path_to_script.js"></script>

Script

$(document).ready(function() {
  if ($("#flashes *").length > 0){
    $("#modalId").modal();
  }
});
Related