I've got a pretty basic flask application in the works and I am having a problem with saving data to a sqlite database that most definitely exists and does take form submissions if I use a direct execute()
method like so:
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
...
gdb = get_db()
gdb.execute("insert into term (term_txt) values (?)", (form.term_txt.data,))
gdb.commit()
The model for which is:
class Term(db.Model):
id = db.Column(db.Integer, primary_key=True)
term_txt = db.Column(db.String(255), unique=True)
def __init__(self, term_txt):
self.term_txt = term_txt
def __repr__(self):
return '<Term %r>' % self.term_txt
The form is:
{% extends "layout.html" %}
{% block body %}
<form action="{{ url_for('addTerm') }}" method="POST">
{{ form.term_text }}
{{ form.csrf_token }}
<p><input type="submit" label="Add Term"></p>
</form>
{% endblock %}
But if I try to use the Flask suggested way of doing it as in this route, i get the following error OperationalError: (sqlite3.OperationalError) no such table: term [SQL: u'INSERT INTO term (term_txt) VALUES (?)'] [parameters: (u'my test term',)]
:
@app.route('/add_term', methods=('GET', 'POST'))
def addTerm():
form = AddTermForm(csrf_enabled=True)
if request.method == "POST":
newTerm = Term(term_txt=form.term_txt.data)
db.session.add(newTerm)
db.session.commit()
#gdb = get_db()
#gdb.execute("insert into term (term_txt) values (?)", (form.term_txt.data,))
#gdb.commit()
return redirect(url_for('terms'))
else:
return render_template('new_term.html', form=form)
db
comes from:
app = Flask(__name__)
app.config.from_envvar('FLASKAPP_SETTINGS', silent=True)
db = SQLAlchemy(app)
As mentioned, the database exists and I can save from the form to the database if I use the above sql command in the code, but I don't feel like that's the best approach.
Also I don't know if the sql command should be in the error or not, maybe something is wrong there. Otherwise, I can't figure out why this isn't working as it appears across a number of docs that this is the way to do it.
Aucun commentaire:
Enregistrer un commentaire