Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url_for in flask when using parameters

Tags:

python

url

flask

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()?

like image 484
Greg Brown Avatar asked Aug 04 '26 11:08

Greg Brown


1 Answers

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.

like image 198
Miguel Avatar answered Aug 07 '26 01:08

Miguel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!