Reputation: 1040
I would like to know if it's possible to have Flask WTForms RadioField render the list of radio buttons in an ordered list instead of an unordered list. My current jinja2 template is as follows:
{% extends "base.html.j2" %}
{% block content %}
<form action="/test" method="POST">
{% if test_form.errors %}
{{ test_form.errors }}
{% endif %}
{{ test_form.csrf_token }}
{% for qa in test_form.question_attempts %}
<div class="well">
<div>
{{ qa.label }}
</div>
<div>
{{ qa }}
</div>
</div>
{% endfor %}
{{ test_form.submitfield(class="btn btn-success") }}
</form>
{% endblock %}
Where the qa
variable is the RadioField input.
EDIT:
To clarify, the test_form
contains a list of RadioFields, which are the question_attempts
. What I would like to do is have each qa
render the radio buttons and associated radio button text in an ordered list rather than an unordered list.
Upvotes: 1
Views: 4557
Reputation: 1040
When reviewing the WTForms documentation I had initially missed the part underneath the RadioFields description which describes how the list of radio buttons are rendered by default. I'll show it below:
{% for subfield in form.radio %}
<tr>
<td>{{ subfield }}</td>
<td>{{ subfield.label }}</td>
</tr>
{% endfor %}
This ends up rendering the radio buttons and associated text in an unordered list. Since I'm making an app where users can take a test, I wanted to render the answer choices in a list of "A. B. etc." This was fairly easy to do - I just needed to explicitly specify how the radio fields in my question_attempt
form needed to be rendered. I'll show my updated code below:
{% extends "base.html.j2" %}
{% block content %}
<form action="/test" method="POST">
{% if test_form.errors %}
{{ test_form.errors }}
{% endif %}
{{ test_form.csrf_token }}
{% for qa in test_form.question_attempts %}
<div class="well">
<div>
{{ qa.label }}
</div>
<div>
<ol type="A">
{% for subfield in qa.answer_selection %}
<li>
{{ subfield }}
{{ subfield.label }}
</li>
{% endfor %}
</ol>
{{ qa.question_id }}
</div>
</div>
{% endfor %}
{{ test_form.submitfield(class="btn btn-success") }}
</form>
{% endblock %}
Now the form renders the radio button fields in and ordered list!
While explicitly writing the template will give you more control for how the fields are rendered, you then need to make sure that each component of the form is rendered in the template. Otherwise data from those fields will not be included in the posted data. This will be obvious for fields that require user input (as you won't see them), but can cause problems if you're using hidden fields for housekeeping data.
Upvotes: 4