Darkened
Darkened

Reputation: 47

Getting None from request.form.get()

I need to get data from 2 different forms. The first "index.html" rendering takes a user's selected option and stores it on the variable "item".

on "page2.html", the "item" value is shown here just fine. And again, the user is entering some new data on the textbox input and then it's redirected to the next rendering, "page3.html"

on "page3.html", it is supposed to show both data from the forms on "index.html" and "page2.html" but i'm getting "None" when I try to show the "item" value. Why?

I've tried to do it on separate app.route() routes, but I got the None type value as well.

the app.py file:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':

            if request.form.get('send') == 'send':
                item = str(request.form.get('test1'))
                return render_template('page2.html', item=item)

            if request.form.get('send2') == 'send2':
                item = str(request.form.get('test1'))
                text = request.form.get('textbox')
                return render_template('page3.html', item=item, text=text)
    else:
        return render_template('index.html')
app.run(debug=True)

the index.html file:

<div align="center">
    <form method="POST" action="{{ url_for('index') }}">
        <select name="test1">
            <option name="1" value="1">1</option>
            <option name="2" value="2">2</option>
            <option name="3" value="3">3</option>
        </select>
        <button type="submit" name="send" value="send">Send</button>
    </form>
</div>

the page2.html file:

<div align="center">
    <form method="POST" action="{{ url_for('index') }}">
        <h2>Previous selection: {{ item }}</h2><br>
        <input type="text" name="textbox" value="Enter text">
        <button type="submit" name="send2" value="send2">Send</button>
    </form>
</div>

and the page3.html file:

<div align="center">
    <h2>Your result is:</h2><br>
    <h2>"{{ text }}" and "{{ item }}" </h2>
</div>

Upvotes: 0

Views: 5872

Answers (1)

iJustin254
iJustin254

Reputation: 62

store the value of item in a session so that you can access it later. Once you are done you can clear the session like session.pop("session_name", None)

if request.form.get('send') == 'send':
    item = str(request.form.get('test1'))
    session["test1"]=item
    return render_template('page2.html', item=item)
if request.form.get('send2') == 'send2':
    item = session.get("test1")
    text = request.form.get('textbox')
    return render_template('page3.html', item=item, text=text)

Upvotes: 1

Related Questions