wtforms:下拉选择器,其值在模型类

时间:2016-06-30 23:13:13

标签: python flask wtforms flask-wtforms

我想为flask-wtforms创建一个模型,其中下拉选择器的值已在模型中定义,因为它们始终相同。我尝试了以下方法:

class DroppdownForm(Form):
    fields = {}
    df = pd.read_excel(open('formfile.xlsx', 'rb'), sheetname='Sheet1')

    df.fillna(value='NA', inplace=True)
    form_fields = ['COLUMN1', 'COLUMN2', 'COLUMN3']

    for form_field_name in form_fields:
        fields[form_field_name] = SelectField(form_field_name, sorted(df[form_field_name].unique().tolist()), description=form_field_name)

观点:

def show_entries():
    form=DroppdownForm()
    return render_template('index.html', form=form)

然后我用

在html文件中渲染它
{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

 {% for field in form %}
     {{ render_field(field) }}
 {% endfor %}

表单为空。我做错了什么?

2 个答案:

答案 0 :(得分:1)

试试这个:

观点:

 <Directory />
    Options FollowSymLinks
    **AllowOverride All**
 </Directory>

模板:

from wtforms import Form, SelectField
import pandas as pd

def DroppdownFormGen(**kwargs):

    class DroppdownForm(Form):
        pass

    df = pd.read_excel(open('MOCK_DATA.xlsx', 'rb'), sheetname='data')
    df.fillna(value='NA', inplace=True)
    form_fields = ['COLUMN1', 'COLUMN2', 'COLUMN3']

    for form_field_name in form_fields:
        label = form_field_name
        field = SelectField(label,choices=list(zip(range(5),sorted(df[form_field_name].unique().tolist()))))
        setattr(DroppdownForm, label, field)

    return DroppdownForm(**kwargs)       


@app.route('/form', methods=['GET'])      
def show_entries():
    form=DroppdownFormGen()
    return render_template('form.html', form=form)

_formhelpers.html在这里http://flask.pocoo.org/docs/0.11/patterns/wtforms/

{% from "_formhelpers.html" import render_field %}

<form method=post action="">

 {% for field in form %}
     {{ render_field(field) }}
 {% endfor %}

  <p><input type=submit value='Submit'>
</form>

答案 1 :(得分:0)

这是获取下拉表单的基本方法。您可以使用valuelabel将数据处理为元组列表。

class DropDown(Form):
    fields = [(value, label), (value, label), (value, label)...]
    dropdown = SelectField('Mydropdown', choices = fields)

Select Field Wtforms

Check out this for more detail