Flask-函数而不是MySQL数据库中的数据

时间:2018-11-19 10:18:50

标签: python flask

我有一个带有WTForms的Flask应用程序,可以处理数据输入。有一个SelectField可以正确显示我在erga表中拥有的数据。但是,在使用表单时,该应用程序没有添加正确的值到数据库表的ergo列中,而是添加了功能!如何解决?

我的表格:

class TestForm(Form):
    testpedio = StringField('Testpedio', [validators.Length(min=1, max=200)])
    erga = SelectField('ergo',  choices=[])

我的代码:

@app.route('/add_test', methods=['GET', 'POST'])
@is_logged_in
def add_test():
    cur = mysql.connection.cursor()
    cur.execute("SELECT ergo FROM erga")
    list1 = list(cur.fetchall())
    def arx():
        for i in list1:
            for k in i:
                j=i[k]
                list2.append(j)

    list2=[]
    arx()
    print(list2)

    form = TestForm(request.form)
    form.erga.choices= [(i,i) for i in list2]
    print(form.erga.choices)

    if request.method == 'POST' and form.validate():
        testpedio = form.testpedio.data

        # Create Cursor
        cur = mysql.connection.cursor()

        # Execute
        cur.execute("INSERT INTO test(testpedio,ergo,author) VALUES(%s,%s, %s)",(testpedio,erga,session['username']))

        # Commit to DB
        mysql.connection.commit()

        #Close connection
        cur.close()

        flash('Test Created', 'success')

        return redirect(url_for('dashboard'))

    return render_template('add_test.html', form=form)

带有SelectField的页面显示一切正常。 Form

MySQL Table

1 个答案:

答案 0 :(得分:0)

您的代码中某处有一个名为remote: Counting objects: 25525, done remote: Finding sources: 100% (396/396) remote: Total 396 (delta 129), reused 376 (delta 129) Receiving objects: 100% (396/396), 167.79 KiB | 2.33 MiB/s, done. Resolving deltas: 100% (129/129), completed with 68 local objects. From <remote-url> * branch refs/x/y/z -> FETCH_HEAD Checking out files: 100% (26834/26834), done. Previous HEAD position was ... HEAD is now at 8315f9bc89 Some extremely old commit that is definitely not refs/x/y/z 的函数。这就是为什么要插入函数而不是值的原因。要修复代码,您将需要从以下位置更改执行语句:

erga

收件人:

cur.execute("INSERT INTO test(testpedio,ergo,author) VALUES(%s,%s, %s)",(testpedio,erga,session['username']))

请注意,我们将执行语句中的cur.execute("INSERT INTO test(testpedio,ergo,author) VALUES(%s,%s, %s)",(testpedio,form.erga.data,session['username'])) 更改为erga,以便在您的表单中获取form.erga.data的值。重要的是要知道SelectField将为您提供所选键的选择。对于您而言,我们不必担心,因为您选择选项的键和值是相同的。但是,在将来的情况下,密钥可能会有所不同。因此,在这种情况下,要获取选择选项的实际值,您可能需要使用form.erga.data