Greg Brown
Greg Brown

Reputation: 1299

Url_for in flask when using parameters

I am trying to use flask's url_for() to navigate to a user's page by passing it the username. I have the html file as

{% for user in users %}
    <li><h2>{{ user.name }}</h2>{{ user.email|safe }}
    <a href="{{ url_for('users_stats',username = {{ user.name }}) }}">stats</a> #This doesn't work
    <a href="/users/{{ user.name }}"> stats </a> #This does work

In my python file I have the function as

@app.route('/users/<username>')
def users_stats(username):
    ...

In which I render another template. Why does the first way not work? Also, since the second way works is it common practice to do urls like that or to use url_for()?

Upvotes: 2

Views: 4405

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67527

Instead of this:

<a href="{{ url_for('users_stats',username = {{ user.name }}) }}">stats</a>

do this:

<a href="{{ url_for('users_stats',username = user.name) }}">stats</a>

You are already inside the {{ and }} block, so you don't need to add a second level of those.

Upvotes: 10

Related Questions