flask - 使用 SQL INSERT 更新表在 Flask App 中不起作用
问题描述
因此,我根据我的挑战搜索了现有问题,但没有找到任何解决方案。我需要通过在创建表期间将新值插入到迄今为止为空的列中来更新数据库的帮助。下面的代码是配置文件的路线。它所做的第一件事是检查是否是登录的用户。如果不是用户,则将用户重定向到登录页面。但是,如果是用户,我希望用户从下拉列表中选择一个值,然后将该值添加到国家列最初设置为 NULL 的用户表中。目前,它没有将记录添加到数据库中。在选择值时,不会在数据库中更新该值。我尝试更新的国家/地区列仍然为空/空
应用程序
@app.route('/profile', methods=['GET', 'POST'])
def profile():
form = CountryForm(request.form) # A drop down list from where user select a value
first = request.form.get('country_select')
if not g.user:
return redirect(url_for('login'))
else:
if request.method == 'POST' and form.validate():
try:
with sqlite3.connect("tour.db") as con:
cur = con.cursor()
print("Opened database successfully")
cur.execute("INSERT INTO users (country) VALUE (?)",(first) )
con.commit()
flash("Record successfully added")
except:
con.rollback()
flash("error in insert operation")
finally:
return render_template("profile.html", msg = first)
con.close()
return render_template('profile.html', user=get_curr_user(), form=form, country=first)
profile.html
{% extends "base.html" %}
{% block head %}
<title>Profile Page</title>
{% endblock %}
{% block body %}
<h1 class="title">
Welcome, {{g.user.username}}
</h1>
<form method="POST" action="{{ url_for('profile') }}">
<select name="country_select">
{% for x in form.country %}
<option>{{ x }}</option>
{% endfor %}
</select>
<input type="submit" value="submit">
</form>
<p>{{country}}</p>
<div class="auth-wrapper">
<a href="{{url_for('logout')}}">Log out</a>
</div>
{% endblock %}
base.html
<html>
<body onload="brython(1)">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% endif %}
{% endwith %}
{% block body %} {% endblock %}
<script type=”text/python” src=”script/program.py”></script>
</body>
</html>
期待您的贡献。谢谢。
解决方案
推荐阅读
- javascript - React ssr(next)-getInitialProps 插入一个 reactNode 到 props 渲染
- mysql - 半同步主主复制
- javascript - 通过键比较两个嵌套对象并获取匹配的对象/数组
- javascript - 如何制作可更新的导航栏?
- java - 如何使用 Google Cloud Storage Java SDK 获取存储桶中最后创建的文件?
- c# - Mediatr IPipelineBehavior 未触发
- php - 查看和编辑 Cloud SQL 表
- mysql - MySQL 每小时一行 00:01:00 和 23:59:00 一天的间隔
- typescript - MaybeSubject:有条件地对内部 observable 应用 shareReplay()
- c# - HttpClient 如何在一个地方捕获每个响应