从表单到数据库输入数据:sqlalchemy.orm.exc.UnmappedInstanceError

时间:2017-07-05 19:53:01

标签: python sql-server-2008 flask-sqlalchemy

请忽略我的黑客工作,我只是试图从插入SQL Server的表单中获取数据。

@app.route("/contact", methods = ['GET', 'POST'])
def contact():
   form = PayRoll_Form()

   if request.method == 'POST':
       if form.validate() == False:
           flash('All fields are required.')
           return render_template('contact.html', form = form)
       else:
           N = engine.execute(PayRoll.insert(),
               Name = request.form['Name'],
               CreateUserPK = request.form['CreateUserPK'],
               PeriodStart = request.form['PeriodStart'],
               PeriodStop = request.form['PeriodStop'],
               DueDate = request.form['DueDate'])
           session.add(N)
           session.commit()
           flash('Submited')
           return redirect("/contact")
   if request.method == 'GET':
       return render_template('contact.html', form = form)
if __name__ == '__main__':
    app.run(debug=True,port=5000)

2 个答案:

答案 0 :(得分:0)

您似乎在混合可能的实现;第N = engine.execute(...行实际上直接对数据库执行INSERT。尝试将结果添加到当前会话并提交该会话没有意义。如果您有一个ORM对象,您对其进行了更改(或已创建)并希望已提交,那么您将只使用这些方法,但您已在上面引用的行中完成此操作。

答案 1 :(得分:0)

解决了这个问题:

@app.route("/contact", methods = ['GET', 'POST'])
def contact():
   form = PayRoll_Form()

   if request.method == 'POST':
       if form.validate() == False:
           flash('All fields are required.')
           return render_template('contact.html', form = form)
       else:
           ins = PayRoll.insert().values(
               Name = request.form['Name'],
               CreateUserPK = request.form['CreateUserPK'],
               PeriodStart = request.form['PeriodStart'],
               PeriodStop = request.form['PeriodStop'],
               DueDate = request.form['DueDate'])
           result = connection.execute(ins)
           flash('Submited')
           return redirect("/contact")
   if request.method == 'GET':
       return render_template('contact.html', form = form)
if __name__ == '__main__':
    app.run(debug=True,port=5000)