gpt4 book ai didi

python - 使用 Flask-Principal 角色填​​充 WTForm MultiCheckboxField

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:14 27 4
gpt4 key购买 nike

我正在为我的 Flask 应用程序编辑用户页面,但我似乎无法弄清楚如何呈现用户的当前角色,就像我处理其他变量(例如电子邮件)一样。

这是我的模型、表单和 View :

#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 列表中的角色?

最佳答案

多选字段的

dataform_data 的列表,在它被您的 coerce 可调用项强制转换后 - 所以您提供需要匹配您提供给 choices 的每个元组中第一个条目的可用内容 - 在本例中为整数。也就是说,如果您将代码更改为:

editform.roles.data = [role.id for role in user.roles]

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

关于python - 使用 Flask-Principal 角色填​​充 WTForm MultiCheckboxField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049034/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com