如何定制WTForm model_表单域映射?

2024-04-25 09:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Flask with Wtforms(和Flask WTF)为模型积垢创建表单。今天我遇到了一个我今天还没弄明白的问题,主要是:

给定以下常量定义:

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

并给出以下模型:

^{pr2}$

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

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

有人能建议修改表单生成,将role(SmallInteger字段)表示为select字段吗?在


Tags: 模型flask表单定义adminwithwtformsrole
1条回答
网友
1楼 · 发布于 2024-04-25 09:14:17

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

相关问题 更多 >