简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM