Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a custom field in wtForms

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.

like image 772
Joel James Avatar asked May 28 '13 18:05

Joel James


1 Answers

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>
like image 170
Doobeh Avatar answered Sep 23 '22 19:09

Doobeh