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()?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With