Getting strange artifacts in URL from Flask's url_for
Question:
I can’t seem to find anything on this particular problem. I’m using the url_for
in an html page and it’s returning some funky stuff right before the query string. What’s causing the below behavior and how can I get the actual URL to match what’s expected?
The call: href="{{ url_for('add_movie', tmdb_id=movie['movie_id']) }}"
Expected URL: ‘/add?tmdb_id=1234’
Actual URL: ‘/add/%7Btmdb_id%7D?tmdb_id=1234′ (the strange part in bold)
The list of movies is populated from a function that makes an API call. I verified that the list of id
‘s returned from the API call looks good.
Python:
class TmdbMovie:
def __init__(self, tmdb_id, title, release_date):
self.movie_id = tmdb_id
self.title = title
self.release_date = release_date
@app.route('/add/{tmdb_id}', methods=['POST'])
def add_movie(tmdb_id):
HTML:
{% for movie in movies %}
<p>
<a href="{{ url_for('add_movie', tmdb_id=movie['movie_id']) }}"> {{ movie['title'] }} - {{ movie['release_date'] }}</a>
</p>
{% endfor %}
Answers:
In the route registration, you have to use angular brackets for parameters:
@app.route('/add/<tmdb_id>', methods=['POST'])
def add_movie(tmdb_id):
The %7B
and %7D
strings are URL-encoded {}
brackets.
I can’t seem to find anything on this particular problem. I’m using the url_for
in an html page and it’s returning some funky stuff right before the query string. What’s causing the below behavior and how can I get the actual URL to match what’s expected?
The call: href="{{ url_for('add_movie', tmdb_id=movie['movie_id']) }}"
Expected URL: ‘/add?tmdb_id=1234’
Actual URL: ‘/add/%7Btmdb_id%7D?tmdb_id=1234′ (the strange part in bold)
The list of movies is populated from a function that makes an API call. I verified that the list of id
‘s returned from the API call looks good.
Python:
class TmdbMovie:
def __init__(self, tmdb_id, title, release_date):
self.movie_id = tmdb_id
self.title = title
self.release_date = release_date
@app.route('/add/{tmdb_id}', methods=['POST'])
def add_movie(tmdb_id):
HTML:
{% for movie in movies %}
<p>
<a href="{{ url_for('add_movie', tmdb_id=movie['movie_id']) }}"> {{ movie['title'] }} - {{ movie['release_date'] }}</a>
</p>
{% endfor %}
In the route registration, you have to use angular brackets for parameters:
@app.route('/add/<tmdb_id>', methods=['POST'])
def add_movie(tmdb_id):
The %7B
and %7D
strings are URL-encoded {}
brackets.