Skip to content
Advertisement

flask python website save user input and add it to the list

this website currently starts out with two input fields at the tope left corner. The first input is the persons name and the second input is the question they have.Currently it just prints successful and unsuccessful. when you press submit button I want the website to print and save the name and question. when a new question is asked it gets added to the list. for example

Danny: how old are U? Tom: when’s ur birthday? Ashley : how tall are you ?

from flask import *

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def basic():
# request.method and request.form
    if request.method == 'POST':
        if request.form['name'] and request.form['pass']:
            return 'Validation successful'
        else:
            return 'Validation unsuccessful'
        return 'Hi'

    return render_template('def.html')


if __name__ == '__main__':
    app.run()



<html>
<head>
</head>
<body>
<form action="/" method="POST">

<input type=text name='name'><br>
<input type=password name='pass'><br>
<input type=submit name='submit'>
</form>

Advertisement

Answer

I think it may help to look into Flask templating, which would allow you to add each response to a list in python, and then re-render the webpage with the new data as shown in this example.

In app.py

from flask import *

app = Flask(__name__)

questions = []
@app.route('/', methods=['GET', 'POST'])
def basic():
    if request.method == 'POST':
        if request.form['name'] and request.form['ques']:
           questions.append({'name': request.form['name'], 'question': request.form['ques']})
    return render_template('def.html', questions=questions)

app.run(debug=True)

In templates/def.html

<html>
<head>
</head>
<body>
{% for question in questions %}
    {{question.name}}: {{question.question}}<br>
{% endfor %}
<form action="/" method="POST">
Name: <input type=text name='name'><br>
Question: <input type=text name='ques'><br>
<input type=submit name='submit'>
</form>

In this example, each time a form is submitted, the questions variable in app.py gets appended to, and then def.html gets re-rendered with the new data.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement