【发布时间】:2020-04-02 12:20:49
【问题描述】:
我正在尝试使用 Flask 制作待办事项列表网络应用程序。我需要创建一个数据库实例来存储任务。出于某种原因,当我尝试制作实例时它不起作用。我确信这是问题所在,因为当我从代码中删除使用数据库的部分时,它运行良好。
这里是代码
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
flask1 = Flask(__name__)
# I think this is telling our app where to look for the database
# Three slashes == relative path. four == absolute path
flask1.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
# initializing the database
db = SQLAlchemy(flask1)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.ctime)
def __repr__(self):
return "<Task %r>" % self.id
# To actually instatiate the database
# 1- start python shell
# 2- import db
# 3- db.create_all()
# 4- exit shell
@flask1.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
task_content = request.form['content']
new_task = Todo(content=task_content)
try:
db.session.add(new_task)
db.session.commit()
return redirect('/')
except:
return 'there was an issue adding the task'
else:
tasks = Todo.query.order_by(Todo.date_created).first
return render_template('index.html', tasks=tasks)
if __name__ == "__main__":
flask1.run(debug=True)
现在在 else 块中,如果我返回 render_template 像 this
return render_template('index.html')
没有错误。这是因为我在 index.html 文件中使用了 tasks 变量
这是产生错误的代码 HTML 代码
<!-- {% for task in tasks %} -->
<tr>
<td>{{ task.content }}</td>
<td> {{task.date_created.date }}</td>
<td>
<a href="">delete</a>
<br>
<a href="">Update</a>
</td>
</tr>
<!-- {% endfor %} -->
我现在遇到的错误是TypeError: 'NoneType' object is not iterable。我相信这意味着我的数据库实例没有成功创建。
我尝试用以下方法创建数据库实例 1-打开python外壳 2-导入此脚本 3- db.create_all() 4-退出python shell
任何帮助表示赞赏 抱歉问了一个很长的问题
【问题讨论】:
标签: python html flask typeerror backend