我想做的是在用 Python Flask 和 SQLAlchemy 编写的 Web 应用程序上实现一个表单,以插入具有特定数据类型(如 2019-10-23 22:38:18)的日期时间。
问题和错误信息
当我编辑
@app.route('/')
def index():
return render_template('index.html', data=Todo.query.all(), form=form)
它返回错误“NameError: name 'form' is not defined”
但是,当我从当前代码中删除 form=form 时,错误已更改为“错误的请求浏览器(或代理)发送了该服务器无法理解的请求。” 单击提交按钮后,在转换后的页面上。
代码
应用程序
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/datetime'
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(), form=form)
千万里不及你
相关分类