【问题标题】:Flask SQLAlchemy inserts null value for text field in PostgreSQL despite textFlask SQLAlchemy 为 PostgreSQL 中的文本字段插入空值,尽管有文本
【发布时间】:2018-08-14 23:44:36
【问题描述】:

books() 方法中的命令基于已经有效的代码。 INSERT INTO 语句是问题所在。当 HTML 表单提交(屏幕底部)时,输入字段文本框中的 userreview 不会被我的 books() 方法拉出并插入到我的 postgres 数据库中,尽管存在文本。为了检查 HTML 页面中的任何内容是否被正确拉入,我测试了隐藏的book_id,它被books() 方法拉出并按预期插入到数据库中。

知道为什么这会坚决拒绝将输入字段中的文本提取到我的方法中并将其插入到我的数据库中吗?

@app.route("/books", methods=["POST"])
@login_required
def books():
    book_id = request.form.get("bookid")
    review = request.form.get("userreview")
    db.execute("INSERT INTO test (review, bookid) VALUES (:review, :bookid)", {"review": review, "bookid":book_id})
    db.commit()

{% block body %}

<div>
    <table class="table">
        <thead>
            <tr>
                <th><strong>Username</strong></th>
                <th><strong>Review</strong></th>
                <th class="text-center"><strong>Rating</strong></th>
            </tr>
        </thead>
        {% for review in reviews %}
        <tr>
            <td>{{ review.username }}</td>
            <td>{{ review.reviews }}</td>
            <td class="text-center">{{ review.rating }}</td>
        </tr>
        {% endfor %}
    </table>
</div>

<form action="{{ url_for('books') }}", method="post">
  <div class="form-group">
    <input name="userreview" type="text" class="form-control" id="bookreview">
    <input type="hidden" name="bookid" value="{{ books.id }}" />
  </div>
  <button type="button" class="btn btn-primary">Submit</button>
</form>

【问题讨论】:

    标签: postgresql flask flask-sqlalchemy


    【解决方案1】:

    这个 HTML 工作得很好,虽然我还没有弄清楚标记的哪一部分造成了差异。我以为是上面代码&lt;form action="{{ url_for('books') }}", method="post"&gt;中的错误逗号,但这没有区别。

    <form action="{{ url_for('books') }}" method="post">
        <fieldset>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form control" name="userreview" type="text"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form control" name="bookid" value="{{ books.id }}" type="hidden"/>
            </div>
            <div class="form-group">
                <button class="btn btn-default" type="submit">Submit</button>
            </div>
        </fieldset>
    </form>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 2017-01-10
      相关资源
      最近更新 更多