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

时间:2013-07-07 22:38:57

标签: python flask wtforms flask-wtforms

我正在使用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'])

有人可以建议修改表单生成代表role(SmallInteger字段)作为选择字段吗?

1 个答案:

答案 0 :(得分:7)

最好尝试使用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()),
    }
})