1

I want to have a form with a set of radio buttons, with each radio button controlling enablement of several other controls, and I want the other controls to be interspersed with the radio buttons. In short, I want something like this:

  • Radio Button
    • Check Box
  • Radio Button
    • Select List
  • Radio Button

where each radio button enables the control immediately below it.

The problem is that Jinja2 wants to render the radio buttons as a group with nothing between them; there doesn't seem to be a clean way to reference the individual button elements.

How do I render the individual radio buttons in the Jinja2 code? I'm using WTForms 2.3.3 and Flask 2.0.1.

For reference, here's the FlaskForm:

def list_sellers():
    c1 = aliased(Contact)
    c2 = aliased(Contact)
    return db.session.query(c2).
        select_from(c1).join(c2, c2.id==c1.seller_id).
        filter(c1.seller_id != None)
    
class ExportForm(FlaskForm):
    filtered = BooleanField('Apply Filters')
    sellers_filter = RadioField(
        'Filter by Seller',
        choices=[
            ('all', 'All Sellers'),
            ('select', 'Select Seller'),
            ('none', 'No Seller')
        ],
        validators=[Optional()]
    )
    seller = QuerySelectField(
        'Seller',
        query_factory=list_sellers,
        allow_blank=False,
        validators=[Optional()],
        render_kw={'class': 'form-select'},
    )
    submit = SubmitField('Download')
Darwin von Corax
  • 5,201
  • 3
  • 17
  • 28

3 Answers3

2

I got something working, but IMHO it's really ugly:

{% for subfield in form.sellers_filter %}
  {% if subfield.id.endswith('0') %}
    <div class="form-group col-4">
      {{ subfield.label }} {{ subfield }}
    </div>
  {% endif %}
  {% if subfield.id.endswith('1') %}
    <div class="form-group col-4">
      {{ subfield.label }} {{ subfield }}
      {{ form.seller }}
    </div>
  {% endif %}
  {% if subfield.id.endswith('2') %}
    <div class="form.group col-4">
      {{ subfield.label }} {{ subfield }}
    </div>
  {% endif %}
{% endfor %}
Darwin von Corax
  • 5,201
  • 3
  • 17
  • 28
0

You can do it in one line as well to have a code a bit shorter without extra "if" statement

{% for subfield in form.sellers_filter if subfield.id.endswith('0')%}
{{ subfield.label }} {{ subfield }}
{% endfor %}
ser-zhm
  • 83
  • 1
  • 8
-1

From my understanding of your question, it's somehow a duplicate here

You need to write javascript code for your purpose.

Titotix
  • 55
  • 7
  • 1
    I have the javascript working; it's getting Jinja2 to render one button element at a time instead of as a group that I'm having trouble with. I should have clarified that in my question, and have since done so. – Darwin von Corax Oct 06 '21 at 10:42