使用Flask-Principal Roles填充WTForm MultiCheckboxField

时间:2014-11-20 20:33:47

标签: python flask jinja2 wtforms flask-principal

我正在为我的烧瓶应用程序编辑用户页面,我似乎无法弄清楚如何呈现用户的当前角色,就像我做其他变量,例如电子邮件。

这是我的模型,表单和视图:

#Flask-Principal Role Model
class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

    def __repr__(self):
        return '<Role %r>' % (self.name)

#SQLALchemy User Model
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key = True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    first_name = db.Column(db.String(128))
    last_name = db.Column(db.String(128))
    business_name = db.Column(db.String(128))
    active = db.Column(db.Boolean())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

#WTForms User Form
class UserForm(Form):
    first_name = StringField('first name', validators= [Required()])
    last_name = StringField('last name', validators= [Required()])
    business_name = StringField('business name', validators= [Required()])
    email = StringField('email', validators = [Required(), Email()])
    active = BooleanField('active')
    roles = MultiCheckboxField('roles', coerce=int)

#Edit User View
@app.route('/admin/users/<id>/edit/', methods = ['GET', 'POST'])
@roles_required('admin')
def edit_user(id):
    user = User.query.filter_by(id = id).first()
    editform = UserForm()

# This is how I've assigned choices for other MultiCheckboxField forms, but I haven't 
# needed to populate the MultiCheckboxField from a user model before with role objects.

    editform.roles.choices = [(x.id,x.name) for x in Role.query.all()]

    if editform.validate_on_submit():
        pass

    editform.first_name.data = user.first_name
    editform.last_name.data = user.last_name
    editform.business_name.data = user.business_name
    editform.email.data = user.email
    editform.active.data = user.active

#The below doesn't show all the available roles, just the current roles assigned.

    editform.roles.data = user.roles


    return render_template("user_edit.html",
        title = "Edit User",
        user = user,
        editform = editform)

那么,有没有人知道如何让WTForms显示所有可用的角色,并检查了当前位于user.roles列表中的角色?

1 个答案:

答案 0 :(得分:3)

多选字段的

dataform_datacoerce来电后强制显示的choices列表 - 所以您提供的内容需要匹配可用的内容作为你提供给editform.roles.data = [role.id for role in user.roles] 的每个元组的第一个条目 - 在这种情况下,是一个整数。也就是说,如果您将代码更改为:

{{1}}

应该看到所有相应的复选框。