尽管有文本,但Flask SQLAlchemy在PostgreSQL中为文本字段插入了空值

时间:2018-08-14 15:01:10

标签: postgresql flask flask-sqlalchemy

books()方法中的命令基于已经起作用的代码。 INSERT INTO语句就是问题所在。提交HTML表单(位于屏幕底部)后,尽管存在文本,但我的userreview方法并没有将输入字段文本框中的books()拉入并插入到我的postgres DB中。为了检查是否正确地从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>

1 个答案:

答案 0 :(得分:0)

此HTML可以正常工作,尽管我还没有弄清楚标记的哪一部分有所作为。我以为上面的代码<form action="{{ url_for('books') }}", method="post">中的错误逗号,但这没什么区别。

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