按钮未在数据库中提交消息

时间:2013-06-19 12:09:06

标签: sqlite flask flask-sqlalchemy

我是一个简单的Flask应用程序,它只存储一个文本字段,在一个网页上,用户应该在其上看到带有“消息”字段的表单。表单下方应该是数据库中现有消息的列表。当用户在“消息”字段中键入内容并提交表单时,“消息”应保存到SQLite中的表中。 AND保存邮件后,用户应返回包含表单和邮件列表的页面。

我陷入困境我无法提交消息 我的页面确实从我创建数据库时已经存储在数据库中的数据库中检索消息。

请有人指导我提交代码以提交表格中填写的信息。

我的连接代码是:

@app.route('/message')
def message():
    g.db = connect_db()
    cur = g.db.execute('select msg_msg from msg')
    message = [dict(msg_msg=row[0]) for row in cur.fetchall()]
    g.db.close()
    return render_template('message.html', message=message)

@app.route('/message', methods=['GET'])
def button():  
    if request.GET.get('Save').strip():
        new = request.GET.get('input_msg').strip()
        g.db = connect_db()
        cur = g.db.execute("INSERT INTO msg (msg_msg) VALUES (?)", (new))
        new_id = c.lastrowid

        g.db.commit()
        g.db.close()

        return '<p>The new input_msg was inserted into the database, the ID is %s</p>' % new_id
    else:
        return render_template('message.html')

AND页面的html代码是

{% extends "template.html "%}
{% block content %}

    <h2>You are in the Message Page</h2>
    <br/>
    <p><h4>In this page, You can view the Existing Messages and can also Submit your own message.</h4></p>
<br/><br/>

<h3>Enter Your Message:</h3><br/>

<form action="/message" methods='GET'>
<dl>
    <dt>Message:
    <dd><input type="text" name="input_msg" maxlength=80   style="width:300px">*Maximum Length = 80
</dl>
<input type=submit value="Save">

</form>

<h3>The Existing Messages:</h3>
{% for item in message %}
Msg_ID: <B>"{{ item.msg_id }}"</B><br/>Message: {{ item.msg_msg }} <br/><br/>
{% endfor %}

{% endblock %}

1 个答案:

答案 0 :(得分:0)

您需要使用POST来处理接收数据。

@app.route('/message', methods=['GET','POST'])
if request.method='POST':
    new = request.form['input_msg'].strip()
    ...
    return redirect(url_for('XXXX'))
else:
    ...
    return render_template('message.html')

德 和你的message.html:

<form action='/message' method='post'>
    <input type="text" name="input_msg" maxlength=80   style="width:300px">
    <input type="submit" value="Save">
</form>

我建议您阅读flask docs,因为您的代码不是标准代码。

相关问题