如何在 HTML 标签中选择信息以在烧瓶形式中使用

我的问题:


有没有办法可以从h4标签之间选择艺术家姓名并使用 Flask 将其传递到数据库中?


语境:


我是 Flask 的新手,所以我可能会在这里犯一些非常简单的错误。我试图让用户点击一个按钮来“关注/喜欢”一位艺术家,当他们这样做时,艺术家的名字将与用户 ID 一起添加到基本数据库中。为此,我正在尝试使用request.form.get('artistName'). 但是,每次都不会返回任何内容。


我的代码的 HTML 如下所示:


{% 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 %}

我的 app.py 如下所示:


@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>'


达令说
浏览 152回答 1
1回答

繁星淼淼

h4不是有效的表单元素,因此您将无法像这样获取它的值。人们通常为此目的使用隐藏输入。试试这个代码:{% for i in range(numOfResults) %}&nbsp; &nbsp; &nbsp;<form method="POST" action="/follow">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div class="col-xs-6 col-sm-3 placeholder">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<img src="{{artistImage[i]}}" width="200" height="200" class="img-responsive" alt="Missing Artist Image">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<h4>{{ artistName[i] }}</h4>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input type="hidden" name="artistName" value="{{ artistName[i] }}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<button type="submit">Follow Artist</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </form>{% endfor %}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python