【问题标题】:No message flashing on Flask without error message没有错误消息在 Flask 上闪烁
【发布时间】:2019-10-23 10:47:05
【问题描述】:

背景和问题

当用户使用 Flask 在 Web 应用程序上正确和错误地输入表单时,我正在尝试实现消息闪烁功能。

当我执行以下程序时,成功从表单向数据库插入数据。

但是,调用消息闪烁失败,没有错误消息。单击“创建”按钮后仅显示插入的数据,并且在我当前的程序上没有消息闪烁。

我应该如何修复我的程序?

官方文档

阅读the official document of Flask Message Flashing!,我不确定我应该如何为我的程序使用密钥。

程序

执行

$ FLASK_APP=app.py FLASK_DEBUG=true flask run

app.py


from flask import Flask, flash, render_template, request, redirect, url_for, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
import sys
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/sample'
db = SQLAlchemy(app)
class Todo(db.Model):
    __tablename__ = 'todos'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    # TODO: implement any missing fields, as a database migration using Flask-Migrate
    def __repr__(self):
      return f'<Todo {self.id} {self.name} {self.city}>'
db.create_all()
@app.route('/todos/create', methods=['POST'])
def create_todo():
  error = False
  body = {}
  
  try:
    name = request.form['name']
    city = request.form['city']
    todo = Todo(name=name, city=city)
    if name == "":
      flash("write your name", "failed")
    elif city == "":
      flash("write your city", "failed")
    db.session.add(todo)
    db.session.commit()
    body['name'] = todo.name
    body['city'] = todo.city
    flash("submitted", "success")
  except:
    error = True
    db.session.rollback()
    print(sys.exc_info())
  finally:
    db.session.close()
  if error:
    abort (400)
  else:
    return jsonify(body)
@app.route('/')
def index():
    return render_template('index.html', data=Todo.query.all())

index.html

<html>
<head>
    <title>Text App</title>
<style>
    .hidden{
        display:  none;
    }
</style>
</head>
<body>
    <form method="post" action="/todos/create">
    <h4>name</h4>
        <input type= "text" name="name" />
    <h4>city</h4>
    <input type= "text" name="city" />
    <input type= "submit" value="Create" />
    </form>
    <div id= "error" class="hidden">Something went wrong!</div>
    <ul>
        {% for d in data %}
    <li>{{d.name}}</li>
        <li>{{d.city}}</li>
        {% endfor %}
    </ul>
    <script>
      const nameInput = document.getElementById('name');
      const cityInput = document.getElementById('city');
      document.getElementById('form').onsubmit = function(e) {
        e.preventDefault();
        const name = nameInput.value;
        const city = cityInput.value;
        descInput.value = '';
        fetch('/todos/create', {
          method: 'POST',
          body: JSON.stringify({
            'name': name,
            'city': city,
          }),
          headers: {
            'Content-Type': 'application/json',
          }
        })
        .then(response => response.json())
        .then(jsonResponse => {
          console.log('response', jsonResponse);
          li = document.createElement('li');
          li.innerText = name;
          li.innerText = city;
          document.getElementById('todos').appendChild(li);
          document.getElementById('error').className = 'hidden';
        })
        .catch(function() {
          document.getElementById('error').className = '';
        })
      }
    </script>
</body>
</html>

环境

Python 3.6.0

烧瓶 1.1.1

SQLAlchemy 1.3.10

psql 11.5

【问题讨论】:

    标签: python html postgresql flask sqlalchemy


    【解决方案1】:

    闪烁的消息不会自动呈现,您必须这样做。这是来自the docs 的示例 jinja 模板代码:

    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
    

    通常的模式是在一个基本模板中包含其他模板扩展的基础模板,以便闪现的消息将显示在它们注册的任何地方。文档会介绍所有这些内容。

    但是,闪烁的消息需要加载页面才能呈现模板,但您使用 AJAX 提交表单并动态呈现输出,因此在用户刷新或导航离开之前消息不会闪烁。

    考虑设置&lt;input&gt; 字段的required 属性,而不是使用flash 向用户传达他们没有填写必填字段:

    <input type= "text" name="name" required/>
    

    Try it.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2011-09-05
      • 2020-04-17
      • 2016-05-09
      • 1970-01-01
      相关资源
      最近更新 更多