其他分享
首页 > 其他分享> > 如何自定义WTForm model_form字段映射?

如何自定义WTForm model_form字段映射?

作者:互联网

我正在使用Flask with Wtforms(和Flask-WTF)来为模型CRUD创建表单.我遇到了一个我今天无法弄清楚的问题,主要是:

给定以下常量定义:

ADMIN = 0
STAFF = 1
USER = 2
ROLE = {
    ADMIN: 'admin',
    STAFF: 'staff',
    USER: 'user'}

并给出以下模型:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(80))
    last_name = db.Column(db.String(80))
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    password = db.Column(db.String(160))
    role = db.Column(db.SmallInteger, default=USER.USER)
    status = db.Column(db.SmallInteger, default=USER.NEW)

并给出以下表单生成代码:

UserEdit = model_form(models.User, base_class=Form, exclude=['password'])

任何人都可以建议修改表单生成,将角色(SmallInteger字段)表示为选择字段吗?

解决方法:

最好尝试使用db.Enum作为角色.但您也可以为您的字段设置自己的小部件:

from wtforms.widgets import Select


class ChoicesSelect(Select):
    def __init__(self, multiple=False, choices=()):
        self.choices = choices
        super(ChoicesSelect, self).__init__(multiple)

    def __call__(self, field, **kwargs):
        field.iter_choices = lambda: ((val, label, val == field.default) 
                                      for val, label in self.choices)
        return super(ChoicesSelect, self).__call__(field, **kwargs)

UserEdit = model_form(User, exclude=['password'], field_args={
    'role': {
        'widget': ChoicesSelect(choices=ROLE.items()),
    }
})

标签:python,flask,wtforms,flask-wtforms
来源: https://codeday.me/bug/20190612/1228586.html