在documentation page上,有一些如何使用WTForms-Alchemy与一对一和一对多关系的例子。我有使用多对多的表格,我似乎无法弄清楚如何渲染这些表单字段。我的代码在下面供参考。
from flask.ext.wtf import Form
from wtforms import Form as Form2
from wtforms_alchemy import model_form_factory, ModelForm, ModelFieldList
from wtforms.fields import FormField
from app.models.bookmodel import Book
from app.models.submodels import BookTypeForm
BaseModelForm = model_form_factory(Form)
BaseSubModelForm = model_form_factory(Form2)
class ModelForm(BaseModelForm):
@classmethod
def get_session(self):
return db.session
class SubModelForm(BaseSubModelForm):
@classmethod
def get_session(self):
return db.session
class BookTypeForm(SubModelForm):
class Meta:
model = BookType
only = ['name']
class BookForm(ModelForm):
class Meta:
model = Book
book_type = ModelFieldList(FormField(BookTypeForm))
这是book_type字段和模型
class BookType(db.Model):
__tablename__ = 'book_type'
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(
ChoiceType(BOOK_TYPES, impl=db.Unicode(16))
)
def __repr__(self):
return "<BookType (name='%s')>" % self.name