我正在尝试使用 wtforms.ext.sqlalchemy QuerySelectMultipleField 显示复选框列表,但我无法让模型数据显示在 GET 的表单上。
这是我的models.py
user_permissions = db.Table('user_permissions',
db.Column('permission_id', db.Integer, db.ForeignKey('permission.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False, unique=True)
email = db.Column(db.String(120), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
permissions = db.relationship('Permission', secondary=user_permissions,
backref=db.backref('permissions', lazy='dynamic'))
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def __repr__(self):
return '<User %r>' % self.username
class Permission(db.Model):
id = db.Column(db.Integer, primary_key=True)
desc = db.Column(db.String(80), nullable=False)
def __init__(self, desc):
self.desc = desc
def __repr__(self):
return '<Permission %r>' % self.desc
这是我的forms.py
class EditUserForm(Form):
username = TextField('Name', validators=[DataRequired()])
email = TextField('Email', validators=[DataRequired()])
permissions = QuerySelectMultipleField(
query_factory=Permission.query.all,
get_label=lambda a: a.desc,
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput()
)
这是我的意见.py
@app.endpoint('edit_user')
@require_login()
@require_permission('edit_user')
def edit_user(user_id):
user = User.query.filter_by(id=user_id).first()
if not user:
abort(404)
data = {
"username": user.username,
"email": user.email,
"permissions": user.permissions
}
form = EditUserForm(**data)
问题在于 WTForm 不显示从 user.permissions 中选择的值,这是 Permission 模型的列表。它显示一个空复选框列表。
(Pdb) print user.permissions
[<Permission u'admin'>, <Permission u'create_user'>, <Permission u'edit_user'>]
我相当确定问题在于“权限”数据值的结构方式,但我已经尝试了我能想到的所有可能性。任何帮助,将不胜感激。
我尝试过的一些事情...
"permissions": [1, 2]
"permissions": ['1', '2']
"permissions": ['permissions-1', 'permissions-2']
"permissions": [('permissions', 1), ('permissions', 2)]
"permissions": [('permissions', '1'), ('permissions', '2')]