python flask-wtf selectfield data导致错误\u mysql\u exceptions.programmingerror

6rqinv9w  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(372)

当我尝试将selectfield中的数据添加到mysql数据库时,出现以下错误:
_mysql\u exceptions.programmingerror\u mysql\u exceptions.programmingerror:在字符串格式化过程中,并非所有参数都已转换
我的代码:

  1. class ContentForm(Form):
  2. category = SelectField("Category: ",choices=[('DataScience','Data Science'), ('ComputerProgramming', 'Computer Programming'),('DigitalMarketing','Digital Marketing'),('Other','Other')], validators=[validators.DataRequired()])
  3. title = StringField("Title: ",validators=[validators.length(min= 5, max = 100), validators.DataRequired()])
  4. content = TextAreaField("Content: ", validators=[validators.length(min = 10), validators.DataRequired()])
  5. @app.route("/addcontent", methods=["GET","POST"])
  6. @login_required
  7. def addcontent():
  8. form = ContentForm(request.form)
  9. if request.method == "POST" and form.validate():
  10. category = form.category.data
  11. title = form.title.data
  12. content = form.content.data
  13. cursor = mysql.connection.cursor()
  14. query = "INSERT INTO contents (author, category, title,content) VALUES(%s,%s,%s)"
  15. cursor.execute(query, (session["username"], category, title, content))
  16. mysql.connection.commit()
  17. cursor.close()
  18. flash("Your content have added successfully. Thanks your contributions.", 'success')
  19. return redirect(url_for("dashboard"))
  20. return render_template("addcontent.html", form = form)

html格式:

  1. {% from "includes/_formhelpers.html" import render_field %}
  2. <form method="post">
  3. {{ render_field(form.category, class="form-control", style = "width: 40% !important") }}
  4. {{ render_field(form.title, class="form-control", style = "width: 40% !important") }}
  5. {{ render_field(form.content, class="form-control", style = "height: 300px !important") }}
  6. <button type="submit" class="btn btn-primary btn-lg">Add Content</button>

我怎样才能解决这个问题?

3pvhb19x

3pvhb19x1#

你的问题来自

  1. cursor.execute(query, (session["username"], category, title, content))

您应该以身份访问会话

  1. session.get('username')

尝试使用某个字符串执行查询以进行测试,以查看它是否会成功执行,如:

  1. cursor.execute(query, 'myName', category, title, content))

相关问题