【问题标题】:Inappropriate datetime datatype and error on Flask AppFlask App 上不适当的日期时间数据类型和错误
【发布时间】:2019-10-23 14:24:03
【问题描述】:

背景

我想做的是在一个用 Python Flask 和 SQLAlchemy 编写的 Web 应用程序上实现一个表单以插入具有特定数据类型(如 2019-10-23 22:38:18)的日期时间。

完整图像

 id |  name  | city    | datetime
----+--------+---------+---------
  1 | Hans   | London |2019-10-23 22:37:10
  2 | John   | NewYork |2019-10-23 22:38:18

数据库

       List of relations
 Schema | Name  | Type  | Owner 
--------+-------+-------+-------
 public | todos | table | username

问题

在添加日期时间列及其表单之前,我已检查是否已成功从表单中插入名称和城市列的数据。但是我在将日期时间从 GUI 表单插入数据库时​​遇到以下错误。

jinja2.exceptions.UndefinedError: 'form' is undefined

程序

app.py

​​>
from flask import Flask, render_template, request, redirect, url_for, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
import sys
import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/simplewr'
db = SQLAlchemy(app)

class Todo(db.Model):
    __tablename__ = 'todos'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String) # Jon
    city = db.Column(db.String(120)) # New York
    datetime = db.Column(db.DateTime()) # 2019-10-23 22:38:18
    def __repr__(self):
      return f'<Todo {self.id} {self.name} {self.city} {self.datetime}>'

db.create_all()

@app.route('/todos/create', methods=['POST'])
def create_todo():
  error = False
  body = {}
  
  try:
    name = request.form['name']
    city = request.form['city']
    datetime = request.form['datetime']
    todo = Todo(name=name, city=city)
    db.session.add(todo)
    db.session.commit()
    body['name'] = todo.name
    body['city'] = todo.city
    body['datetime'] = todo.datetime
  except:
    error = True
    db.session.rollback()
    print(sys.exc_info())
  finally:
    db.session.close()
  if error:
    abort (400)
  else:
    return jsonify(body)


# Filters
def format_datetime(value, format='medium'):
  date = dateutil.parser.parse(value)
  if format == 'full':
      format="EEEE MMMM, d, y 'at' h:mma"
  elif format == 'medium':
      format="EE MM, dd, y h:mma"
  return babel.dates.format_datetime(date, format)

app.jinja_env.filters['datetime'] = format_datetime

@app.route('/')
def index():
    return render_template('index.html', data=Todo.query.all())

index.html

<html>
<head>
  <title>Todo 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" />
    <div>
    <label for="datetime">Date Time</label>
    {{ form.datetime(class_ = 'form-control', placeholder='YYYY-MM-DD HH:MM', autofocus = true) }}
    </div>
    <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>
    <li>{{d.datetime}}</li>
    {% endfor %}
  </ul>
    <script>
      const nameInput = document.getElementById('name');
      const cityInput = document.getElementById('city');
      const dtInput = document.getElementById('datetime');
      document.getElementById('form').onsubmit = function(e) {
        e.preventDefault();
        const name = nameInput.value;
        const city = cityInput.value;
        const datetime = dtInput.value;
        descInput.value = '';
        fetch('/todos/create', {
          method: 'POST',
          body: JSON.stringify({
            'name': name,
            'city': city,
            'datetime': datetime,
          }),
          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;
          li.innerText = datetime;
          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

PostgreSQL 11.5

【问题讨论】:

    标签: python html datetime flask flask-sqlalchemy


    【解决方案1】:

    首先,您正在以一种非常规的方式使用您的form。并不是说它错了,只是它与典型的不同,这使得googling 寻求帮助更加困难。

    现在回答你的问题...

    您收到此错误的原因是您没有传递form 变量供您的模板使用。您的索引路线看起来像:

    @app.route('/')
    def index():
        return render_template('index.html', data=Todo.query.all(), form=form)
    

    但是上述方法不起作用,因为您尚未在 index() 路由中定义表单。因此,您必须像在 jinja 模板中为 namecity 那样实现 datetime 属性。而不是:

    {{ form.datetime(class_ = 'form-control', placeholder='YYYY-MM-DD HH:MM', autofocus = true) }}
    

    您需要自己创建 html。例如:

    <input id="datetime" type="datetime-local">
    

    您可以查看docs 以查看用于指定datetime-local 输入类型的所有选项。

    【讨论】:

    猜你喜欢
    • 2020-11-06
    • 2016-12-14
    • 2012-06-07
    • 2022-01-20
    • 2014-04-02
    • 2018-12-03
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多