Search code examples
pythonflaskflask-sqlalchemyflask-wtformswerkzeug

How to select information within a HTML tag to use in a flask form


My question:

Is there a way that I can select the artist name from between the h4 tags and pass it into the database using Flask?

Context:

I am new to flask so I could be making some pretty simple mistakes here. I am trying to allow a user to click a button to 'follow/like' an artist and when they do this the artists name will be added to a basic database along with the users ID. To do this I am trying to use request.form.get('artistName'). However, each time this does not return anything.

The HTML for my code looks like:

{% for i in range(numOfResults) %}
     <form method="POST" action="/follow">
         <div class="col-xs-6 col-sm-3 placeholder">
             <img src="{{artistImage[i]}}" width="200" height="200" class="img-responsive" alt="Missing Artist Image">
             <h4 name='artistName'>{{ artistName[i] }}</h4>
             <button type="submit">Follow Artist</button>
          </div>
      </form>
{% endfor %}

My app.py looks as follows:

@app.route('/follow', methods=['GET', 'POST'])
def follow():
    artistName = request.form.get('artistName')
    new_like = Like(user_id=current_user.id, artist=artistName, artist_id='10')
    db.session.add(new_like)
    db.session.commit()
    return '<h1> Artist Followed </h1>'


Solution

  • h4 is not a valid form element, so you will not be able to get its value like this. One usually uses hidden input for such purpose.

    Try this code:

    {% for i in range(numOfResults) %}
         <form method="POST" action="/follow">
             <div class="col-xs-6 col-sm-3 placeholder">
                 <img src="{{artistImage[i]}}" width="200" height="200" class="img-responsive" alt="Missing Artist Image">
                 <h4>{{ artistName[i] }}</h4>
                 <input type="hidden" name="artistName" value="{{ artistName[i] }}">
                 <button type="submit">Follow Artist</button>
              </div>
          </form>
    {% endfor %}