我正在编写一段代码,要求用户从复选框中选择浇头,他们可以选择多个。当他们按下提交时,我想返回将从数据库中查询的浇头列表。 当我运行程序时,我可以选中多个复选框,但是当我按下“提交浇头”按钮时,出现以下错误:
sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type.
[SQL: INSERT INTO pizza_topppings (toppings) VALUES (?)]
[parameters: (['Pepperoni', 'Extra', 'Cheese'],)]
(Background on this error at: http://sqlalche.me/e/13/rvf5)
我如何解决此问题,以便程序返回选定的浇头?
这是代码
app.py
import os
from flask_wtf import FlaskForm
from flask import Flask, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from forms import ToppingForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app,db)
class PizzaTopppings(db.Model):
id = db.Column(db.Integer, primary_key=True)
toppings = db.Column(db.Text)
def __init__(self, toppings):
self.toppings = toppings
def __repr__(self):
return f"Toppings requested: {self.toppings}"
@app.route('/')
def index():
return render_template('index.html')
@app.route('/addtopping', methods=['GET', 'POST'])
def add_toppings():
form = ToppingForm()
if form.validate_on_submit():
toppings = form.toppings.data
new_toppings = PizzaTopppings(toppings)
db.session.add(new_toppings)
db.session.commit()
return redirect(url_for('list_toppings'))
return render_template('add_toppings.html', form = form)
@app.route('/listoftoppings')
def list_toppings():
pizza_toppings = PizzaTopppings.query.all()
return render_template('toppinglist.html', pizza_toppings= pizza_toppings)
if __name__ == '__main__':
app.run(debug=True)
forms.py
from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, SubmitField, widgets
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class ToppingForm(FlaskForm):
string_of_files = ['Pepperoni\r\nExtra Cheese\r\nGreen Peppers\r\nSpinach\r\nPineapple']
list_of_files = string_of_files[0].split()
# create a list of value/description tuples
files = [(x, x) for x in list_of_files]
toppings = MultiCheckboxField('toppings', choices=files)
submit = SubmitField('Submit toppings')
add_toppings.html
{% extends 'base.html' %}
{% block content %}
<div class="jumbotron">
<h1>Customer Information</h1>
<p>Provide your information to begin your order.</p>
<form method="POST">
{{form.hidden_tag()}}
{{form.toppings.label}} {{form.toppings()}}
{{form.submit()}}
</form>
</div>
{% endblock %}
toppinglisy.html
{% extends 'base.html' %}
{% block content %}
<div class= 'jumbotron'>
<h1>Order Toppings Here</h1>
<ul>
{% for t in pizza_toppings %}
<li>{{t}}</li>
{% endfor %}
</ul>
</div>
{% endblock content %}
谢谢您的帮助。