Flask wtform RadioField label does not render

2019-07-24 19:48发布

问题:

When using the following form:

class TextForm(Form):
    example = RadioField('Choice 1:', choices=[('A','Option A'),('B','Option B')])
    key = RadioField('Choice 2:', choices=[('1', 'Option 1'), ('2', 'Option 2')])
    submit = SubmitField('Submit')

I am expecting to see:

Choice 1:

  • Option A
  • Option B

Choice 2:

  • Option 1
  • Option 2

Instead I am getting no labels as follows:

  • Option A
  • Option B
  • Option 1
  • Option 2

What am I missing?

回答1:

I don't use quick_form but if you are going to render the field label, you need to place the {{ field.foo.label }} and {{ field.foo }} for the field label to show, something like this works for me:

<form method="POST" action="/">
    {{ form.hidden_tag() }}
    <h3>{{ form.example.label }}</h3>
    <p>{{ form.example }}</p>
    <h3>{{ form.key.label }}</h3>
    <p>{{ form.key }}</p>
    {{ form.submit }}
</form>

Updated:

Just tried on flask-bootstrap, it should work if rendering the field labels and fields like above (but instead using wtf.form_field, however I'm not seeing anything about quick_form, perhaps a bug? Anyway, here's the working sample:

{% import "bootstrap/wtf.html" as wtf %}

<h3>{{ form.example.label }}</h3>
<p>{{ wtf.form_field(form.example) }}</p>

<h3>{{ form.key.label }}</h3>
<p>{{ wtf.form_field(form.key) }}</p>

{{ form.submit }}

Hope this helps, and output:



回答2:

I just had the same issue.

It might be intended by the author of "quick_form" macro, or more likely he/she missed a line of code to render out the label of RadioField, as the same is done for other types of fields.

To hack it, locate the file "bootstrap/wtf.html", where macro "quick_form" is defined.

add this line:

{{field.label(class="control-label")|safe}}

before the "for" loop:

{% for item in field -%}
  <div class="radio">
    <label>
      {{item|safe}} {{item.label.text|safe}}
    </label>
  </div>
{% endfor %}

Hope this works for you.



回答3:

This is a bug in Flask-Bootstrap, there are two PR opened to fix this (#159 and #166).

Currently, if you use Bootstrap 4, then you can try to use Bootstrap-Flask, a replacement for Flask-Bootstrap.