url_for() parameter was ignored in flask


My route method is:

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 “”,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



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

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

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

def movie(page_num=1):
    return str(page_num)

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

if __name__ == '__main__':
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.