Daniels0n
Daniels0n

Reputation: 93

Optional keyword argument in render_template

Here is my code:

@app.route('/', methods=['GET', 'POST'])
def index():
    form = CryptoForm()
    if session.get('currency'):
        currency = session.get('currency')
        price1 = Get_info(currency)
        price = price1.get_filtered_data()
    if form.validate_on_submit():
        flash('success', 'success')
        currency = form.crypto.data
        get_price = Get_info(currency)
        session['currency'] = get_price.get_filtered_data()
        return redirect(url_for('index'))
    return render_template("index.html", form=form, price=price)

What I'm trying to do is to get the user to type a crypto acronym into the form and submit it. When the user submits it, it should display the price. But when the page loads for first time there is no price so the price=price in render_template is giving me error. How could I fix it so there is a price only if he submit the form?

Upvotes: 0

Views: 161

Answers (1)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9746

If you want to do different things whether the form is submitted or not, check what the method is.

from flask import request

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # The user submitted something.
    else:
        # The user fetched something.

Upvotes: 1

Related Questions