oceandye
oceandye

Reputation: 319

How to correctly send variables to Flask Route using url_for()?

I have seen a couple of other questions such as this one asking for ways to send variables from HTML back to flask using url_for() and so I tried it too.

{% for movie in movies %}
       <article class="media content-section">
         <div class="media-body">
           <div class="article-metadata">
             <h3><a class="mr-2 mt-4" href="{{url_for('movies', movie_id=movie.id)}}" method="POST">{{ movie.title }}</a></h3>
             <small class="text-muted">{{ movie.year }}</small>
             <small class="text-muted">ID : {{ movie.id }}</small>
           </div>
           <h6><a class="article-title">Rating : {{ movie.rating }}</a></h6>
         </div>
       </article>
    {% endfor %}

As seen in line 5, I did a url_for() and sent a variable called movie_id which was the id attribute of my movie object to my route which looked like this,

@app.route('/movies/<movie_id>', methods=['GET','POST'])
def movies(movie_id):
    if request.method == 'POST':
        movie = Movie.query.filter_by(id=movie_id).first()
    return render_template('movies.html', movie=movie)

However, upon running the code, I get the error saying that UnboundLocalError: local variable 'movie' referenced before assignment. This occurs at the last line of my route return render_template('movies.html', movie=movie). May I know where I went wrong?

Upvotes: 0

Views: 333

Answers (1)

Aldric
Aldric

Reputation: 507

You are only querying for the movie if the request method is 'POST'

Perhaps you got an error because you were calling the route with a 'GET' method instead. This would typically be the case if you're just accessing the URL directly from the browser (without using forms etc).

Try removing that if statement

Upvotes: 2

Related Questions