Search code examples
pythonflaskflask-restful

How to get form field in handler Flask?


I have got some input fields in Flask form:

<input type="time" name="time[0]"/>
<input type="time" name="time[1]"/>
<input type="time" name="time[2]"/>

I tried to get these input values like:

values = request.args.get('time')

for v in values
    print v

But it does not work for me.

Also as I know correct I can not use <input type="time" name="time[]"/>


Solution

  • A minimal flask server I have,

    from flask import request
    from flask import Flask
    from flask import render_template
    
    app = Flask(__name__)
    
    @app.route('/', methods=['GET', 'POST'])
    def login():
        values = request.args.getlist('time[]')
        print values
        values = request.form.getlist('time[]')
        print values
    
        if request.method == 'POST':
          # The logic may goes here...
          return render_template('test.html')
        else:
            return render_template('test.html')
    

    HTML template(test.html) is,

    <form method="get">
    <input type="time" name="time[]"/>
    <input type="time" name="time[]"/>
    <input type="time" name="time[]"/>
    <input type="time" name="time[]"/>
    <input type="submit"/>
    </form>
    

    When the form is submitted after the times are entered, below is how I'm able to collect the data.

    values = request.args.getlist('time[]')
    print values # Printed [u'17:06', u'09:00', u'22:01', u'07:08']
    

    When the form's method is changed to "post", I'm getting the data with,

    values = request.form.getlist('time[]')
    print values # Printed [u'17:06', u'09:00', u'22:01', u'07:08']
    

    Hopefully, should work! Let me know if my snippets have been deviating from your requirement.