1

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

我被困在一个点我无法提交消息我的页面确实从数据库中检索消息,这些消息在我创建时已经存储在数据库中。

但是请有人指导代码以提交表格中填写的消息。我的 message.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="" method='POST'>
<dl>
    <dt>Message:
    <dd><input type="text" name=msg_msg maxlength=80  style="width:300px">*Maximum Length = 80
</dl>
<input type=submit value="Submit Message">

</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 %}



and my routes.py code for this is:


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

@app.route('/message', methods=['GET', 'POST'])
    def message_1():
    error = None
    if request.method == 'POST':
    for request.form['input_msg'] = text:
        g.db = connect_db()
        cur = g.db.execute('insert into msg_msg from msg')
        message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
        g.db.close()
        return render_template('message.html', message=message)

        #error = 'Invalid Entry, Please Try Again.'
else:
#   session['logged_in'] = True
    return redirect(url_for('message'))
return render_template('message.html' , error=error)
4

1 回答 1

1

使用 1 个消息视图

@app.route('/message', methods=['GET', 'POST'])
def message():
    cur = db.execute('select id,msg from msg_msg')
    message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
    if request.method == 'POST':

        g.db = connect_db()
        cur = g.db.execute('insert into msg_msg (msg) values (?)',request.form['input_msg'])
        message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
        g.db.close()

    return render_template('message.html' , message = message)

消息.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={{ url_for('message') }} method='POST'>
<dl>
<dt>Message:
<dd><input type="text" name=msg_msg maxlength=80  style="width:300px">
</dl>
<input type=submit value="Submit Message">

</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 %}
于 2013-06-18T19:20:34.407 回答