Question

I have a form with a TextField, FileField, and I want to add a RadioField.

I'd like to have a radio field with two options, where the user can only select one. I'm following the example of the two previous forms that work.

My forms.py looks like this

    from flask import Flask, request
    from werkzeug import secure_filename
    from flask.ext.wtf import Form, TextField, BooleanField, FileField, file_required,         RadioField
    from flask.ext.wtf import Required
    class ImageForm(Form):
        name = TextField('name', validators = [Required()])
        fileName = FileField('fileName', validators=[file_required()])
        certification = RadioField('certification', choices = ['option1', 'option2'])

In my views.py file I have

form = myForm()
if form.validate_on_submit():
    name = form.name.data
    fileName = secure_filename(form.fileName.file.filename)
    certification = form.certification.data

In my .html file I have

     {% block content %}
     <h1>Simple Form</h1>
     <form action="" method="post" name="simple" enctype="multipart/form-data">
         {{form.hidden_tag()}}
         <p>
             Name:
             {{form.name(size=80)}}
         </p>
         <p>
             Upload a file
             {{form.fileName()}}
         </p>
         <p>
             Certification:
             {{form.certification()}}
         </p>
         <p><input type="submit" value="Submit"></p>
     </form>
     {% endblock %}

I can't seem to find examples online of someone using a radio button form. I found a description of RadioField here http://wtforms.simplecodes.com/docs/0.6/fields.html

When I try to visit the my form page I get the DEBUG error "ValueError: too many values to unpack"

Was it helpful?

Solution

In the forms.py the RadioField needs to look like this

    RadioField('Label', choices=[('value','description'),('value_two','whatever')])

Where the options are 'description' and 'whatever' with the submitted values being 'value' an 'value_two' respectively.

OTHER TIPS

form.certification() won't work. You need to iterate over the values in the template:

Replace:

{{ form.certification() }}

with:

{% for subfield in form.certification %}
<tr>
    <td>{{ subfield }}</td>
    <td>{{ subfield.label }}</td>
</tr>
{% endfor %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top