首页 > 解决方案 > render_template 中的可选关键字参数

问题描述

这是我的代码:

@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)

我要做的是让用户在表单中输入加密首字母缩写词并提交。当用户提交它时,它应该显示价格。但是当页面第一次加载时没有价格,所以price=priceinrender_template给了我错误。我怎样才能解决它,只有当他提交表格时才有价格?

标签: pythonflask

解决方案


如果无论是否提交表单,您都想做不同的事情,请检查它是什么method

from flask import request

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

推荐阅读