Home > database >  Python & Flask HTML - Making n number of textboxes based on variable
Python & Flask HTML - Making n number of textboxes based on variable

Time:12-14

I have a flask webpage I am trying to create. When users register for an account, they declare the number of agricultural fields they have. This is saved in a MySQL database. From this, I need users to add information on another input page. This input page should have "n" number of textboxes based on the number of fields they have.

Is there anyway to create "n" number of textboxes in HTML? I can read in the number of fields from their account but cannot find a way to create a variable number of textboxes within HTML. I do not need this to be dynamic (the user add or remove) this needs to be a FIXED amount of textboxes.

CodePudding user response:

Found a solution, it is a little ugly but should work.

in your html:

<table>
         {% for x in range(fields | int) %}
             <tr>
                    <td>
                <input type="text" value="{{ x }}">
                    </td>
                </tr>
            {% endfor %}
        </table>

in python:

def irrigation_input():
   ...... non important stuff here.....
        fields=account_info_irr[9]
        int(float(fields))
            
        return render_template('irrigationinput.html',fields=fields)

CodePudding user response:

I'm going to assume that because of flask you are using jina2 as your rendering engine, let's call the number of fields that need to be created n, you can just use the loop structure

{% for i in range(n) %}
   <input name="field-{{i}}" />
{% endfor %}

you can get more info at https://jinja.palletsprojects.com/en/3.0.x/templates/#for

if you need more complex forms, I would recommend using WTForms.

  • Related