0

I am new to Flask and I'm trying to build a simple web app. Basically what I have on the home page is a text input box and a submit button. After clicking submit, it shows some result based on the text that was inputted (for now it's hardcoded in the code below).

What I want is when you click submit, it should not only show the result but also a button to add the inputted text to a specific file. However, I am struggling to get this to work (the "Add to dataset" button doesn't do anything).

Here is what I have for now:

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')

    # if submit button is clicked
    if request.form['submit'] == 'Submit':
        # get the text from the form that was filled in
        input_text = request.form['text']

        final_result = 'stackoverflow rocks'

        return render_template('index.html', result=final_result, text=input_text)

    if request.form['add-dataset'] == 'Add to dataset':
        f = open('dataset/dataset.tsv', 'a')
        f.write(input_text)

The index.html:

<!doctype html>
<head>
    <link rel="stylesheet" media="screen" href ="static/bootstrap.min.css">
    <link rel="stylesheet" href="static/bootstrap-theme.min.css">
    <meta name="viewport" content = "width=device-width, initial-scale=1.0">
</head>
<br/>
<div class="container">
    <form action="/" method="post" role="form">
        <div class="form-group">
            <label for="text">Text:</label>
            <input type="text" class="form-control" name="text" placeholder="Input sentence here">
            <br />
        </div>
        <input type="submit" name="submit" value="Submit" class="btn btn-success">
    </form>
    <br/>

    {% if result is not none %}
        <div class="alert alert-success">
            {{ result }}
        </div>
        <h2>Add to dataset</h2>
        <br/><input type="submit" name="add-dataset" value="Add to dataset" class="btn btn-success">
    {% endif %} 
</div>
</html>
4
  • However, I am struggling to get this to work. What does that mean exactly ? Be more specific to address your actual problem. Commented Jul 23, 2018 at 12:33
  • The code I used above doesn't work, it's complaining about indents for some reason. I know it's not correct like this, because it's actually a form inside another form (in this case just a button), but I don't know how to do it... As I said, I'm totally new to Flask. Commented Jul 23, 2018 at 12:38
  • I understand, but it will be hard for us to help you if we don't actually know what are your problems. Commented Jul 23, 2018 at 12:39
  • Sorry, the indents weren't the issue. The issue is just that clicking the new button "add to dataset" doesn't do anything. I edited my question :) Commented Jul 23, 2018 at 12:42

2 Answers 2

1

Just wondering ... why can't you add onClick property to the button so when you click it , you handle something like

HTML:

<input type="submit" onclick="(function(){
                               alert('Hey i am calling');
                               })();" />

Instead of alert , use fetch API to send data to server or do whatever you want to

API

@app.route("/somepath",methods=["GET","POST"])
def handler():
    data =  request.get_json()
    //process the data here
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the reply. Is it also possible in this case to show a message on the screen? Sorry I'm not used to web development at all and I'm new to Flask. Can you tell me how to do the JS part?
yes , google about flask flash, there is a method in flash called as get_flashed_messages() . Usage is pretty simple .. follow this link for showing the message flask.pocoo.org/docs/1.0/patterns/flashing
Ok thanks. Can you tell me how to do the JS part? I'm not familiar with JS at all sorry.
What does that mean? Sorry I'm not a web developer.
Ok thank you but how do I add Python code to that JS code? So to open a file in Python and append the inputted text to it.
0

the second

 <input>

is missing

 <form>

so the browser doesn't do anything

try this:

python:

if request.method=='POST':
    input_text=request.form['text']
    if request.form['submit']=='Submit':
  final_result = 'stackoverflow rocks'
  return render_template('index.html', result=final_result, text=input_text)
    elif request.form['action']=='addToDataset':
  f = open('dataset/dataset.tsv', 'a')
  f.write(input_text)
        return redirect(url_for('index'))
    else:
        render_template('index.html')
else:
    return render_template('index.html')

html:

  <div class="container">
        <form method="post" role="form">
            <div class="form-group">
                <label for="text">Text:</label>
                <input type="text" class="form-control" name="text" placeholder="Input sentence here">
                <br />
            </div>
            <input type="submit" name="submit" value="Submit" class="btn btn-success">
        </form>
        <br/>

        {% if result is not none %}
            <div class="alert alert-success">
                {{ result }}
            </div>
            <h2>Add to dataset</h2>
            <br/>
            <form method="post" role="form">
                <div class="form-group">
                    <label for="text">Text:</label>
                    <input type="text" class="form-control" name="text" placeholder="Input sentence here">
                    <br />
                </div>
                <input type="submit" name="submit" value="addToDataset" class="btn btn-success">
            </form>
        {% endif %} 
    </div>

4 Comments

When I put input_text=request.form['text'] before the if request.form['submit']=='Submit': I get the error werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'text' and I know why. You first input text in the text box and then click submit, but when you click submit the text in the text box disappears. So when you then try to click the positive/negative buttons it tries to get the text from the text box, but there is none.
what positive / negative buttons? and why do you have it before 'if request'
Sorry I mean the "add to dataset" button
do you want to use 1 input form and 2 buttons? if so, then use my python, but remove the entire second form and just add input button from 2nd to first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.