How to make a RadioField in Flask?

泄露秘密 提交于 2019-12-09 09:53:41

问题


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"


回答1:


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.




回答2:


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 %}


来源:https://stackoverflow.com/questions/14591202/how-to-make-a-radiofield-in-flask

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