how to use Flask Jinja2 url_for with multiple para

2019-03-15 16:10发布

everyone!

I got an problem while i was using jinja2 url_for() function.

I have a route like:

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

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

2条回答
我命由我不由天
2楼-- · 2019-03-15 16:31

You missed a dot, try that:

url_for('.article_page', article_id=article.id, url_title=article.url_title)
查看更多
Anthone
3楼-- · 2019-03-15 16:52

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.

查看更多
登录 后发表回答