【问题标题】:Button click in HTML to update SQLAlchemy db in Flask在 HTML 中单击按钮以更新 Flask 中的 SQLAlchemy db
【发布时间】:2018-03-13 21:50:14
【问题描述】:

我正在尝试通过单击按钮为 Flask Web 应用程序的登录用户更新名为“收藏夹”的数据库值。本质上,收藏夹列是一个看起来像这样的单个字符串:Apples, Bananas, Oranges 在单击按钮的位置,我想通过将字符串拆分为@app.routes() 中的列表来附加一个值(比如Cherries),附加值,并在提交更改之前将其重新加入字符串。我不确定这样做的正确方法是什么,这就是我所拥有的:

HTML sn-p

<button action="{{ url_for('add') }}" method="post" type="submit">Favorite</button>

@app.routes()

@app.route('/add', methods=['POST'])
def add():
    star_faves = current_user.favorites
    star_faves_list = star_faves.split(', ')
    star_faves_list.append('Cherries')
    ', '.join(star_faves_list)
    current_user.favorites = star_faves_list
    db.session.commit()
    return render_template('add.html')

问题是我不太了解 HTML 是如何与 Python/Jinja 进行通信的,如果有人能帮助澄清这一点,我将不胜感激。

【问题讨论】:

    标签: python flask jinja2 flask-sqlalchemy


    【解决方案1】:

    您似乎混淆了某些元素。

    如果要向/add 页面提交POST 请求,最简单的方法是创建一个表单。 (按钮没有动作或方法属性,表单有。)创建表单时,还指定提交表单时要使用的 HTTP 方法。所以在你的情况下,它应该是这样的:

    <form action="{{ url_for('add') }}" method="POST">
         <input type="submit" value="Favorite">
    </form>
    

    您可以使用按钮而不是类型为提交的输入,它们是interchangeable。

    如果您不希望页面在提交请求时重新加载,您可以在 JavaScript 中使用一种更高级的技术,称为 AJAX。

    此示例代码将相同的 POST 请求发送到/add 页面:

    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        // this method gets called if the state of the request changes (it succeeds of fails)
        // you will probably want to update your page accordingly here
    };
    request.open('POST', '/add');
    request.send();
    

    【讨论】:

    • 谢谢@martonbognar,我想我现在对逻辑理解得更好了,我的python和HTML sn-p之间的通信现在已经启动并运行了。至于数据库更新,我意识到我没有将', '.join() 语句保存到变量中。分配最终成功了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 2021-11-11
    • 2020-12-12
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多