J
J
JRazor2014-08-08 23:51:43
Flask
JRazor, 2014-08-08 23:51:43

Flask: how to build a simple form?

Dear colleagues.

I decided to try to build a simple web form for parsers. The choice fell on Flask (because of its ease), but here the creation of forms is described in it, I will say, not so hot.

We need a very simple form:
e67d362322fe41dab80baccd8d51fe37.jpg

The first is just a Label, which should be sent to the module for further work.
The second is a button to upload an image. Well, almost loading: just read the path to this image.
By pressing the Start button, one of them (filled) should go to another module.

Everything seemed to be simple. But Flask is not very friendly with native forms, and WTForms is some kind of whopper.

Can anyone advise something about this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
euspensky, 2014-08-11
@JRazor

a very detailed post about forms in flask.
Specifically, such a form can be done like this:

from flask_wtf import Form, TextField, FileField
class PuziForm(Form):
    image_url = TextField("label1")
    image = FileField("label2")

@app.route('/test', methods=['GET', 'POST'])
def test():
    form = PuziForm()
    if form.validate_on_submit():
        result = (form.image.data and form.image.data.read()) or form.image_url.data
    else:
        result = 'not submitted'
    return render_template('test.html', form=form, result=result)

<form method="post" enctype=multipart/form-data>
        {{ form.hidden_tag() }}
        {% for element in form %}
            {% if element.widget.input_type != 'hidden' %}
                {{ element.label }} {{ element() }} <br>
            {% endif %}
        {% endfor %}
        <input type="submit">
    </form>
<br>
{{ result }}

add rounded corners to taste.

S
s1dney, 2014-08-12
@s1dney

wtf is convenient in working with large and complex forms, and when it is necessary to generate these forms dynamically and conveniently, saving yourself from unnecessary code in templates,
and if you need a form with 3 fields, why put extra dependencies on flask if it all fits into 5 lines without wtf:

<form>
<input type="text">
<input type="file">
<button type="submit">OK</button>
</form>

@app.route('/test', methods=['GET', 'POST'])
def test():
  form = request.form

X
xzfallen, 2015-10-29
@xzfallen

book Developing web applications using Flask in Python my-files.ru/tol0cr

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question