简体   繁体   中英

Flask Newbie Query sqlite3.OperationalError

I am newbie trying to learn flask by creating a simple todo app for this is below the python code i ham trying to execute but when i run i am getting sqlite3.OperationalError: no such column: todo.task i am unsure what i am missing here kindly assist

import os
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy


project_dir = os.path.dirname(os.path.abspath(__file__))
# sqlite: // / prefix to tell SQLAlchemy which database engine we're using.
database_file = "sqlite:///{}".format(
    os.path.join(project_dir, "mydatabase.db"))

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)


class Todo(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    task = db.Column(db.String(100))


@app.route('/', methods=["GET", "POST"])
def samplehome():
    todo_list = Todo.query.all()
    print(todo_list)

    
    return render_template("index.html", todo_list=todo_list)

    # if request.form:
    #     print(request.form)
    #     submitted = Todo(id=request.form.get("id"),task=request.form.get("task"))
    #     try:
    #         db.session.add(submitted)
    #         db.session.commit()
    #     except Exception as e:
    #         print(e)
    #         db.session.rollback()
    



if __name__ == "__main__":
    db.create_all()
    app.run(host='0.0.0.0', debug=True)

I think problem is you are not committing changes after db.create_all() function. You can try like this.

if __name__ == "__main__":
    db.create_all()
    db.session.commit()
    app.run(host='0.0.0.0', debug=True)

There is a similar question : SQLAlchemy create_all() does not create tables

Apart from your question, i dont suggest directly return your db class. You can checkout MVC design pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM