带多个参数的Flaskurl_for()

2024-05-23 19:05:05 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

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

你知道如何克服构建错误吗?

我试过的:

Creating link to an url of Flask app in jinja2 template

用于对url_for()使用多个参数

Build error with variables and url_for in Flask

相似的建造错误

顺便说一下,这个函数的目的是当有人点击“下一页”按钮时遍历一个列表。我正在传递变量i,这样我就可以有一个引用在列表中不断递增。有没有一种烧瓶/金贾2的方法更有效?我已经研究了循环列表功能,但它似乎不能用于呈现页面,然后使用cycling_list.next()重新呈现页面。


Tags: formurl列表forsearchmore错误action
2条回答

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

@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

您的路由不指定如何填写多于一个past_val参数。Flask无法神奇地创建一个URL,如果不给它一个双参数模式,它将传递两个参数。

相关问题 更多 >