url_for() parameter was ignored in flask

Question:

My route method is:

@app.route('/movie/')
def movie(page_num=1):
#...detail skipped...

And my template is:

<li><a href="{{ url_for('movie',page_num=page_num) }}">{{ page_num }}</a></li>

When I click the link, the address bar shows “127.0.0.1:5000/movie/?page_num=5”,but the pagination.page shows it is still page 1.

Why the parameter was ignored and how can I fix it?

Asked By: Yancheng Zeng

||

Answers:

Since you skipped the code of your function it’s hard to say what’s wrong. But I suspect that you just don’t catch GET parameters correctly. To do this you can either use variable rules with dynamic name component in your route; or access parameters submitted in the URL with request.args.get.

Here’s a minimal example showing boths methods:

from flask import Flask, url_for, request
app = Flask(__name__)

@app.route('/')
def index():
    link = url_for('movie',page_num=5)
    return "<a href='{0}'>Click</a>".format(link)

@app.route('/index2')
def index_get():
    link = url_for('movie_get',page_num=5)
    return "<a href='{0}'>Click</a>".format(link)


@app.route('/movie/<page_num>')
def movie(page_num=1):
    return str(page_num)

@app.route('/movie_get')
def movie_get():
    param = request.args.get('page_num', '1')
    return str(param)

if __name__ == '__main__':
    app.run(debug=True)
Answered By: vrs
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.