TypeError:url_for()只取1个参数(给定2个)

时间:2018-03-12 16:18:39

标签: html5 python-2.7 flask jinja2

使用jinja2时,我的html模板出错了。这是我得到的错误:TypeError:url_for()只取1个参数(给定2个)。在endif语句之后,错误发生在2个td标记中。我尝试在按钮内部使用onclick,这是我知道如何添加url_for标记的另一种方式。

这是我使用的模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title> 
</head>
<body>
    <table align="center" id="comic_list">
        {% for value in bobby %}
        <tr>
            <td> {{ value[0]|safe }} </td>
            <td> {{ value[1]|safe }} </td>
            <td> {{ value[2]|safe }} </td>
            <td> {{ value[3]|safe }} </td>
            <td> {{ value[4]|safe }} </td>
            <td> {{ value[6]|safe }} </td>
            <td> {{ value[7]|safe }} </td>
        </tr>
        {% endfor %}
        <tr>
            <td><a href="{{url_for('test', next)}}"><button type="submit" value="Next">Next</button></a></td>
            <td><a href="{{url_for('test', prev)}}"><button type="submit" value="Prev">Previous</button></a></td>
        </tr>
    </table>
</body>
<footer>
        <p align="right">Date/Time: <span id="datetime"></span></p>
        <script>
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();
        </script>
    </footer>
</html>

这是使用的python代码:

@app.route('/test')
def test():

    current_page = request.args.get('page', 1, type=int)
    comic_dic = {}
    per_page = 10
    bob = create_bob('Book', 'Yes')
    end = (current_page * per_page) + 1
    if end > len(bob):
        end = len(bob)
    start = ((current_page - 1) * per_page) + 1

    bob[1:] = sorted(bob[1:], key=lambda v: (v.publisher, v.sort, v.character, v.publication_date, int(v.volume)))

    bobby = []
    bobby.append(bob[0:1])
    for result in bob[start:end]:
        bobby.append(result)
    next = 'page=' + str(current_page + 1)
    prev = 'page=' + str(current_page - 1)
    comic_dic['bob'] = bobby
    comic_dic['next'] = current_page + 1
    comic_dic['prev'] = current_page - 1

    return render_template('yes.html', bobby=bobby, next=next, prev=prev)

谢谢Zach

1 个答案:

答案 0 :(得分:1)

这是url_for()的文档: http://flask.pocoo.org/docs/0.12/api/#flask.url_for

你的问题是url_for只接受一个参数(如错误所示)。但它需要额外的关键字参数。例如,如果您希望以当前的方式传递next和prev变量,则只需将代码更改为:

<tr>
  <td><a href="{{url_for('test', page=next)}}"><button type="submit" value="Next">Next</button></a></td>
  <td><a href="{{url_for('test', page=prev)}}"><button type="submit" value="Prev">Previous</button></a></td>
</tr>

这将生成如下所示的链接:

    <tr>
        <td><a href="example.com/test?page=3"><button type="submit" value="Next">Next</button></a></td>
        <td><a href="example.com/test?page=1"><button type="submit" value="Prev">Previous</button></a></td>
    </tr>

当然,我假设您展示的第一个模板是下一个传递的,而变量分别是3和1。