在wtForms中创建自定义字段

时间:2013-05-28 18:56:12

标签: wtforms flask-wtforms

在我的表单中,我正在尝试创建一个带有选项的自定义数组字段。

自定义表单字段:

class CustomField(Field):
    widget = TextInput()
    def _value(self):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []

实际表单调用自定义表单字段

class PostForm(Form):

    status = CustomField()

每当我将数据发布到PostForm时,它都会调用自定义字段,但不会将任何valuelist传递给process_formatdata。自定义字段始终返回空列表。
我在这里遗漏了什么。

1 个答案:

答案 0 :(得分:8)

您的代码适合我,这是一个有效的例子 -

example.py

from flask import Flask, render_template
from flask.ext.wtf import Form, SubmitField, Field, TextInput

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Shh!'


class CustomField(Field):
    widget = TextInput()

    def _value(self):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []


class ExampleForm(Form):
    status = CustomField()
    submit = SubmitField('POST')


@app.route('/', methods=['post', 'get'])
def hello_world():
    form = ExampleForm()
    if form.validate_on_submit():
        for entry in form.status.data:
            print '{}'.format(entry)
    return render_template('test.html', form=form)


if __name__ == '__main__':
    app.run(debug=True)

模板/的test.html

<form action="." method="post">
    {{ form.hidden_tag() }}
    {{ form.status }}
    {{ form.submit }}
</form>