I'm building a contact manager with Flask for a community group, and I'm working on the function to export contacts as a spreadsheet. I want to export either all contacts, only those who have been assigned to a ticket seller, only those assigned to a specific ticket seller, or those assigned to no ticket seller.

The form layout I want is something like this:

  • RadioButton: All Sellers
  • RadioButton: Select Seller
    • SelectField: Seller ID
  • RadioButton: No Seller Assigned

with a select field tucked in between two of the radio buttons. This requires that I render the radio buttons individually, rather than letting Jinja render them as a group. This is possible, but referencing each individual button for rendering has proven difficult.

Here's the Jinja code I've come up with:

{% for subfield in form.sellers_filter %}
  {% if subfield.id.endswith('0') %}
    <div class="form-group col-4">
      {{ subfield.label }} {{ subfield }}
  {% endif %}
  {% if subfield.id.endswith('1') %}
    <div class="form-group col-4">
      {{ subfield.label }} {{ subfield }}
      {{ form.seller }}
  {% endif %}
  {% if subfield.id.endswith('2') %}
    <div class="form.group col-4">
      {{ subfield.label }} {{ subfield }}
  {% endif %}
{% endfor %}

I'm bothered, though, by the subfield.id.endswith() part, and I'm hoping someone can suggest a more elegant solution.

For reference, here is my form code:

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',
            ('all', 'All Sellers'),
            ('select', 'Select Seller'),
            ('none', 'No Seller')
    seller = QuerySelectField(
        render_kw={'class': 'form-select'},
    submit = SubmitField('Download')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.