动态创建WTForm的SelectField元素

2024-06-07 19:10:47 发布

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

我的数据库中有一个表,其中包含一些员工,每个员工都有一个分配的任务id。我想根据具有特定任务id的员工数量动态创建选择字段。例如,如果有3个员工的任务id1,则会有三个选择字段(每个字段都有5下拉项) 在表格.py你知道吗

 class DynamicForm(Form):
    @classmethod 
    def append_field(cls, name, field):
        setattr(cls, name, field)
        return cls  

在路线.py--主文件

assigns = Project_Users.query.filter_by(project_id=id).all() 
// query the database to get all the staff under the project using the project id 
l = len(assigns) // length/ number of staff

d = DynamicForm() // from form.py
for e in range(l):         
  d.append_field(assigns[e].admin.first_name,SelectField(assigns[e].admin.first_name, validators=[DataRequired()], choices=[('0', 'No Task'),( '1','Site Acquisition'),('2','Installation'),('3','Configuration'), ('4','Commission')]))

    d.append_field('submit', SubmitField('SAVE')) // this is outside the for loop

在html模板中

<form action="/project/{{ project.id }}/tasks" method="POST">
                  {{ d.hidden_tag() }}
                <table class="table is-stripped" style="width: 100%;">
                    <tbody>
                      {% for g in d %}
                      <tr>
                        <td>{{ g.label }}</td>
                        <td>{{ g }}</td>
                      </tr>
                      {% endfor %}

                      </tbody>
                  </table>
              </form>

上面的代码正在工作,但是它没有改变,职员的数量也在改变例如,项目1有3个职员,它显示了3个selectfields,但是当项目2有2个职员,它显示了3个职员和3个selectfields时


Tags: thenamepyformprojectidfieldfor
1条回答
网友
1楼 · 发布于 2024-06-07 19:10:47

尝试用参数动态覆盖构造函数来构造窗体:

class DynamicForm(Form):
    submit = SubmitField

    def __init__(self, **kwargs):
        assigns = Project_Users.query.filter_by(project_id=kwargs['id']).all()
        for ass in assigns:         
            setattr(DynamicForm,
                    ass.admin.first_name,
                    SelectField(ass.admin.first_name, 
                                validators=[DataRequired()], 
                                choices=[('0', 'No Task'),
                                         ( '1','Site Acquisition'),
                                         ('2','Installation'),
                                         ('3','Configuration'),
                                         ('4','Commission')]))
        super().__init__()

那你就这样说吧

d = DynamicForm(id=1)

从技术上讲,这与表单的区别在于,在初始化表单之后,在运行基Form之后添加类级属性。也就是说:

DynamicForm(Form):
    def __init__(self)
        super().__init__() # calls Form.__init__()
        # extra stuff

以及

DynamicForm(Form):
    def __init__(self)
        # extra stuff
        super().__init__() # calls Form.__init__() and acts on extra stuff.

相关问题 更多 >

    热门问题