how to use Flask Jinja2 url_for with multiple parameters

Tiny Lin picture Tiny Lin · Dec 28, 2013 · Viewed 49.4k times · Source

I have a problem while using jinja2 url_for() function.

I have a route like this:

@app.route('/article/<int:article_id>/<url_title>/', methods=['GET'])
def article_page(article_id, url_title):
    article = Article.query.get(article_id)
    if article == None:
        abort(404)
    return render_template('article.html', article=article)

in jinja template file,i want to create a url which links to article_page,so i write like this:

<h5>
  <a href="{{ url_for('article_page',article_id=article.id,url_title=article.url_title) }}">{{ article.title }}</a>
</h5>

but when I run this page, I get a error:

raise BuildError(endpoint, values, method)
BuildError: ('article_page', {'article_id': 1}, None)

It seems like that the second parameter url_title missing. How can I use url_for() with multiple parameters correctly?

Answer

falsetru picture falsetru · Dec 28, 2013

According to url_for documentation:

If the value of a query argument is None, the whole pair is skipped.

Make sure that url_title is not None.

Or specify default value for url_title in the article_page function.