用烧瓶显示多个flash消息

时间:2017-09-18 00:30:18

标签: python flask flash-message

我正在尝试使用flask在我的html上显示多个flash消息,以确定验证表单可能出现的任何错误。现在只有一个。有没有办法做到这一点?可能有一些空白列表,错误消息进入,然后在html端迭代该列表?

蟒:

@app.route("/user", methods=['POST'])

def create_user():

    if len(request.form["name"]) < 1:
        flash("Name cannot be blank")
        return redirect("/")
    else:
        session["name"] = request.form["name"]
        session["location"] = request.form["location"]
        session["language"] = request.form["language"]
    if len(request.form["comment"]) > 120:
        flash("Comment cannot be longer than 120 characters")
        return redirect("/")
    elif len(request.form["comment"]) < 1:
        flash("Comment cannot be blank")
    else:
        session["comment"] = request.form["comment"]

    return redirect("/results")

HTML:

{% with messages = get_flashed_messages() %}
    {% if messages %}
        {% for message in messages %}
            <p>{{ message }}</p>
        {% endfor %}
    {% endif %}
{% endwith %}
<form action="/user" method="POST" accept-charset="utf-8">
    <label>Name:</label>
    <div id=right>
        <input type="text" name="name">
    </div>
    <label>Location:</label>
    <div id=right>
        <select name="location">
        <option value="location1">Location 1</option>
        <option value="location2">Location 2</option>
        </select>
    </div>
    <label>Language:</label>
    <div id=right>
        <select name="language" >
        <option value="choice1">Choice 1</option>
        <option value="choice2">Choice 2</option>
        </select>
    </div>
    <label>Comment (optional):</label>
    <textarea name="comment" rows="5", cols="35"></textarea>
    <button type="submit">Submit</button>
</form>

1 个答案:

答案 0 :(得分:2)

您绝对可以显示多条Flash消息,这是默认行为。问题是您的代码路径从不允许多条Flash消息,因为您在调用redirect后立即返回flash。您可以像这样重构代码:

@app.route("/user", methods=['POST'])

def create_user():

    errors = False

    if len(request.form["name"]) < 1:
        flash("Name cannot be blank")
        errors = True
    else:
        session["name"] = request.form["name"]
        session["location"] = request.form["location"]
        session["language"] = request.form["language"]

    if len(request.form["comment"]) > 120:
        flash("Comment cannot be longer than 120 characters")
        errors = True
    elif len(request.form["comment"]) < 1:
        flash("Comment cannot be blank")
        errors = True
    else:
        session["comment"] = request.form["comment"]

    if errors:
        return redirect("/")
    else:
        return redirect("/results")