简体   繁体   中英

Flash Messages aren't appearing on page

I'm creating a currency converter using python and flask, and trying to flash error messages for invalid inputs. The form automatically routes to the error checks upon submission. I have been manipulating the inputs to purposely raise errors and a KeyError is showing in my browser, but not flashing on my page.

These are the checks I'm trying to do:

def check_valid_code():
    converting_from = (request.form['converting_from']).upper()
    converting_to = (request.form['converting_to']).upper()
    c= CurrencyCodes()
    try:
         c.get_symbol(converting_from)
    except KeyError:
        flash("{converting_from} is not a valid currency code!")
    
    try:
         c.get_symbol(converting_to)
    except KeyError:
        flash("{converting_to} is not a valid currency code!")

def check_valid_number():
    amount = request.form['amount']
    if amount.isnumeric() == True:
        amount= float(amount)
        return amount
    else:
        flash("Not a valid amount.")

My base.html (using Bootstrap) where the messages should appear:

<body>
  <div class="container" style="min-height:100% width:80%">
    <div class="col-sm-4">
      {% with errors = get_flashed_messages(category_filter=["danger"]) %}
          {% if errors %}
              {%- for message in errors %}
                  <div class="alert alert-danger alert-dismissible fade show" role="alert">
                      <span>{{ message }}</span>
                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                      </button>
                  </div>
              {% endfor -%}
          {% endif %}
      {% endwith %}
  </div>
    {% block content %}
    {% endblock %}
  </div>
</body>

You should use render_template library from Flask and your code looks like this:

from flask import Flask, render_template

def check_valid_code():
    converting_from = (request.form['converting_from']).upper()
    converting_to = (request.form['converting_to']).upper()
    c= CurrencyCodes()
    try:
         c.get_symbol(converting_from)
    except KeyError:
        message = "{converting_from} is not a valid currency code!"
    
    try:
         c.get_symbol(converting_to)
    except KeyError:
        message = "{converting_to} is not a valid currency code!"

return render_template('base.html',message=message)

def check_valid_number():
    amount = request.form['amount']
    if amount.isnumeric() == True:
        amount= float(amount)
        return amount
    else:
        message = "Not a valid amount."

return render_template('base.html',message=message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM