ValueError: too many values to unpack (expected 2) in flash in Flask

Viewed 530

I am having a ValueError (ValueError: too many values to unpack (expected 2)) in my Flask App. I came to know that this is because of flash that I am using to display a message with a category in it.

The problem occurs, when I try this

{% with messages = get_flashed_messages() %}
  {% if messages %}
    {% for category, msg in messages %}

      <div class="alert {{category}}">
        <h1>{{category}}:</h1>
        <h4>{{msg}}</h4>
      </div>

    {% endfor %}
  {% endif %}
{% endwith %}

But if I just remove the category from the for loop it works, but the category doesn't!

{% with messages = get_flashed_messages() %}
  {% if messages %}
    {% for msg in messages %}

      <div class="alert {{category}}">
        <h1>{{category}}:</h1>
        <h4>{{msg}}</h4>
      </div>

    {% endfor %}
  {% endif %}
{% endwith %}

Please help me

2 Answers

i guess you're missing to set the second parameter, the category of the message (it could be error, warning whatever ..) for flash() in your view function

flash(u'Invalid password provided', 'error')

don't forget to set with_categories=true in get_flashed_messages() function:

{% with messages = get_flashed_messages(with_categories=true) %} {# --HERE--  #}
  {% if messages %}
    {% for category, msg in messages %}

      <div class="alert {{category}}">
        <h1>{{category}}:</h1>
        <h4>{{msg}}</h4>
      </div>

    {% endfor %}
  {% endif %}
{% endwith %}

refer to this doc

I have found out what to do, the problem was I had to mention that I want to use the category in jinja

{% with messages = get_flashed_messages(with_categories=true) %}

{% with messages = get_flashed_messages(with_categories=true) %} 
  {% if messages %} 
     {% for category, msg in messages %}
        <div class="alert {{category}}">
          <h4>{{msg}}</h4>
        </div>
     {% endfor %}
  {% endif %}
{% endwith %}
Related