首页 > 解决方案 > 使用 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”&gt;</script>
</body>
</html>

期待您的贡献。谢谢。

标签: flaskflask-sqlalchemyflask-wtforms

解决方案


推荐阅读