简体   繁体   English

带有字段名称的Flask WTForms动态可编辑表字段

[英]Flask WTForms Dynamic Editable Table Fields with Field Names

How can I get the Field Names to return as text/string? 如何获得以文本/字符串形式返回的字段名称?

Highlighted "Field Names" I want returned as text, not fields 我想以文本而非字段的形式返回突出显示的“字段名称”

I am dynamically creating a list of fields and then appending values. 我正在动态创建字段列表,然后附加值。 But I can't seem to figure out a way to return the field names as plain text. 但是我似乎无法找出一种将字段名称返回为纯文本的方法。 The below code appends them to a field (fieldname)-- which is the only way I have been able to return them. 下面的代码将它们附加到字段(fieldname)上,这是我能够返回它们的唯一方法。

class ContractFields(FlaskForm):
    fieldname = StringField()
    fieldvalue = StringField()

class ContractForm(FlaskForm):
    title = StringField('title')
    contractfieldlist = FieldList(FormField(ContractFields))

@app.route('/tester.html', methods=['GET','POST'])
def contractfields():
    form = ContractForm()
    for f in object:
            document_form = ContractFields()
            document_form.fieldname = f.name #need this list object to return as table text, not a field
            document_form.fieldvalue = f.value

            form.contractfieldlist.append_entry(document_form)

    return render_template('tester.html', form = form)

And from the template: 并从模板:

 <div> <form action="" method="post" name="form"> {{ form.hidden_tag() }} <div> <table> <tr> <th> ListNumber </th> <th> Field Name </th> <th> Field Value </th> </tr> {% for items in form.contractfieldlist %} <tr> <td>{{ items.label }}</td> <td>{{ items.fieldname }}</td> <td>{{ items.fieldvalue }}</td> </tr> {% endfor %} </table> </div> <p><input type="submit" name="edit" value="Send"></p> </form> </div> 

My experience with Python has largely been limited ETL and data transformation so I don't understand why this was so complicated. 我在Python方面的经验在很大程度上受限于ETL和数据转换,所以我不明白为什么这么复杂。 But after way too many hours I finally found the following solution worked for me . 但是经过太多的时间,我终于发现以下解决方案对我有用

Specifically modifying the associated excerpt from the above post to be the following: 专门将以上文章中的相关摘录修改为以下内容:

class ContractFields(FlaskForm):
        fieldname = HiddenField()
        fieldvalue = StringField()
        def __init__(self, *args, **kwargs):
                super(ContractFields, self).__init__(*args, **kwargs)
                if 'obj' in kwargs and kwargs['obj'] is not None:
                        self.fieldvalue.label.text = kwargs['obj'].fieldname

And the template html to: 和模板html可以:

      <td>{{ items.label }}</td>
      <td>{{ items.fieldvalue.label }}</td>
      <td>{{ items.fieldvalue }}</td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM