How to make a RadioField in Flask?

2020-06-15 02:05发布

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"

2条回答
再贱就再见
2楼-- · 2020-06-15 02:22

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.

查看更多
女痞
3楼-- · 2020-06-15 02:31

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 %}
查看更多
登录 后发表回答