具有多个参数的 Flask url_for()

新手上路,请多包涵

问题:

我在表单中有一个输入按钮,当它提交时应该将两个参数 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>

烧瓶功能:

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

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

我试过的:

在 jinja2 模板中创建指向 Flask 应用程序 url 的链接

在 url_for() 中使用多个参数

在 Flask 中使用变量和 url_for 构建错误

类似的构建错误

作为旁注,该函数的目的是在有人点击“下一页”按钮时遍历列表。我正在传递变量 i 以便我可以参考以在列表中不断递增。有没有更好用的 flask / jinja 2 方法?我查看了 cycling_list 功能,但它似乎无法用于呈现页面,然后使用 cycling_list.next() 重新呈现它。

原文由 agconti 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 770
2 个回答

您的路线没有指定如何填写一个 past_val arg。如果你不给它一个双参数模式,Flask 就不能神奇地创建一个将传递两个参数的 URL。

原文由 Amber 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 @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

原文由 plaes 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题