我尝试使用Flask从HTML表单中获取值列表,并将其存储在数据库的Column中。我试图使用getlist()但我不知道应该如何以正确的方式做到这一点。
数据库:
association_table = Table('association', Base.metadata,
Column('book_id', Integer, ForeignKey('Book.id')),
Column('form_id', Integer, ForeignKey('Form.id'))
)
class Book(Base):
__tablename__ = 'Book'
name = Column(String(80), nullable = False, unique=True)
id = Column(Integer, primary_key = True)
author = Column(String(30))
language = Column(String(30))
category_id = Column(Integer, ForeignKey('Category.id'), nullable = False)
category = relationship(Category)
forms = relationship("Form", secondary=association_table, back_populates="books")
def __repr__(self):
return '<Book %r>' % self.name
class Form(Base):
__tablename__ = 'Form'
name = Column(String, nullable = False)
id = Column(Integer, primary_key=True)
books = relationship("Book", secondary=association_table, back_populates="forms")
def __repr__(self):
return self.name
新书模板:
<p>Choose Form</p>
<select name=form method="GET" action="/" multiple>
{% for form in forms %}
<option value= "{{form}}" SELECTED>{{ form }}</option>"
{% endfor %}
</select>
路线:
@app.route('/books/new/', methods=['GET', 'POST'])
def newBook():
categories = session.query(Category).all()
forms = session.query(Form).all()
#languages = session.query(Languages).all()
if request.method == 'POST':
newBook = Book(name = request.form['name'],
author = request.form['author'],
category = Category(name=request.form.get('category')),
forms = Form(name=request.form.getlist('form')),
language = request.form['language'])
session.add(newBook)
session.commit()
flash("New Book Added!")
return redirect(url_for('showBooks'))
else:
return render_template('newBook.html', languages=languages, categories=categories, forms=forms)
当我尝试添加新书时,我得到TypeError: 不兼容的集合类型:表单不是类似列表的
答案 0 :(得分:0)
创建Book
实例时,您应该将Form
实例列表传递给Book
的构造函数。
book = Book(name=request.form["name"],
author=request.form["author"],
language=request.form["language"],
category=request.form["category"],
forms=[Form(name) for name in request.form.getlist("form")])