Skip to content Skip to sidebar Skip to footer

Rendering Flask HTML Forms Results In "UnboundLocalError"

I want to make a Flask application that receives the details from a user. After a successful registration, a new page will be displayed showing the entered details. The application

Solution 1:

result only exists if the request method is POST, so if the request method was GET(which is the default request one), that is when the page is requested before submitting user data form, then result won't be existing, hence the error message. Plus, you need to render the result object into another template, for example user.html:

@app.route('/register',methods = ['POST', 'GET'])
def user():
    if request.method == 'POST':
        result = request.form
        name =  result['name']
        phoneno = result['phoneno']
        email = result['email']
        password = result['password']
        if name or phoneno or email or password is not None:
            print name,phoneno,email,password
            return render_template("user.html",result=result)
    return render_template("register.html")

Another thing, if the above view function is for register.html form, then you also need to change in form block, from:

<form action = "/success" method = "POST">

to

<form action = "/register" method = "POST">

Solution 2:

Try this:
app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def form():
    return render_template('register.html')


@app.route('/success',methods = ['POST', 'GET'])
def user():
    if request.method == 'POST':
        results = request.form
    return render_template('new.html',results=results)

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

new.html

{% for k,v in results.iteritems() %}
    <p>{{v}}</p>
{% endfor %}

register.html is the same as yours.
You are missing a html template to display your form input data, new.html file will render the values you enter in your form.


Post a Comment for "Rendering Flask HTML Forms Results In "UnboundLocalError""