Create a custom field in wtForms

会有一股神秘感。 提交于 2019-12-10 13:37:07

问题


In my form I am trying to create a custom array field with choices.

The custom form field:

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 = []

The actual form calls the custom form field

class PostForm(Form):

    status = CustomField()

Whenever, I post data to PostForm it calls the custom field but does not pass in an any valuelist to process_formatdata. The custom field always returns a empty list.
Am I missing any thing here.


回答1:


Your code works for me, here's a working example--

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)

templates/test.html

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


来源:https://stackoverflow.com/questions/16799388/create-a-custom-field-in-wtforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!