我的问题。
有没有一种方法可以让我选择艺术家的名字,从之间的 h4
标签,并使用Flask将其传入数据库?
上下文。
我是flask的新手,所以我可能犯了一些很简单的错误。我试图让用户点击一个按钮来 "followlike "一个艺术家,当他们这样做的时候,艺术家的名字将和用户的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>'
h4
不是一个有效的表单元素,所以你不能像这样获得它的值。人们通常使用隐藏输入来达到这样的目的。
试试这段代码。
{% 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 %}