4

我正在使用带有 Wtforms(和 Flask-WTF)的 Flask 来为模型 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 字段)表示为选择字段的表单生成吗?

4

1 回答 1

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()),
    }
})
于 2013-07-08T06:40:32.207 回答