python - 具有多个参数的 Flask url_for()

标签 python html flask

问题:

我在表单中有一个输入按钮,当它提交时应该将两个参数 search_vali 重定向到 more_results() 函数,(在下面列出),但在构建 wsgi 时出现类型错误。

错误是:TypeError: more_results() takes exactly 2 arguments (1 given)

html:

 <form action="{{ url_for('more_results', past_val=search_val, ind=i ) }}" method=post>
    <input id='next_hutch' type=submit value="Get the next Hunch!" name='action'>
 </form>

flask 函数:

@app.route('/results/more_<past_val>_hunches', methods=['POST'])
def more_results(past_val, ind):
    
    if request.form["action"] == "Get the next Hunch!":
        ind += 1 
        queried_resturants = hf.find_lunch(past_val) #method to generate a list
        queried_resturants = queried_resturants[ind]
        return render_template(
                               'show_entries.html', 
                                queried_resturants=queried_resturants, 
                                search_val=past_val,
                                i=ind 
                               )

关于如何克服构建错误的任何想法?

我尝试过的:

Creating link to an url of Flask app in jinja2 template

通过 url_for() 使用多个参数

Build error with variables and url_for in Flask

类似的构建错误

作为旁注,该函数的目的是在有人点击“下一页”按钮时循环访问列表。我正在传递变量 i 以便我可以有一个引用来在列表中保持递增。有没有更好用的 flask/jinja 2 方法?我研究了 cycling_list 功能,但它似乎无法用于呈现页面,然后使用 cycling_list.next() 重新呈现它。

最佳答案

也可以通过为某些参数指定默认值来创建支持可变数量参数的路由:

@app.route('/foo/<int:a>')
@app.route('/foo/<int:a>/<int:b>')
@app.route('/foo/<int:a>/<int:b>/<int:c>')
def test(a, b=None, c=None):
   pass

关于python - 具有多个参数的 Flask url_for(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17873820/

相关文章:

python - 创建带有前缀标签的 XML 文件(python 和 lxml)

python - 根据 Django 模型中的条件根据需要创建模型字段

CSS - 我的 HTML 和 BODY 之间的空白

javascript - 自动单击单选按钮但首先检查句子(标签)?

python - 在 Flask-sqlalchemy 和 Postgresql 中使用 JSON 类型

python - 语法错误 : missing ; before statement

python - 在 python 中使用 bson.json_util.loads 时如何忽略时区?

html - 在 Internet Explorer 中使用自动对焦时模态中奇怪的光标放置

python - 无法比较原始偏移和偏移感知日期时间 - last_seen 选项

javascript - Jinja2 中的 {% now 'U' %} 实现?