python - 为 flask 投票应用程序输入选项

标签 python html sqlite flask jinja2

我为使用 Flask 制作的投票应用程序制作了一个数据库模式,如下所示:

CREATE TABLE questions (
    question_id integer primary key autoincrement,
    questiontext string not null
);

CREATE TABLE choices (
    choice_id integer primary key autoincrement,
    choicetext string not null,
    question_id integer,
    FOREIGN KEY(question_id) REFERENCES questions(question_id)
);

但我想不出我应该如何询问(在 HTML 模板中)并将选项插入数据库。我的 'show_polls' 和 'add_polls' 在下面

    @app.route('/')
def show_polls():
    cur = g.db.execute('SELECT questiontext, choicetext FROM questions q JOIN choices c ON c.question_id = q.question_id') 
    polls = [dict(question=row[0], choices=(c for c in row[1:])) for row in cur.fetchall()] 
    return render_template('show_polls.html', polls=polls)

@app.route('/add', methods=['POST'])
def add_poll():
    if not session.get('logged_in'):
        abort(401)
    g.db.execute('insert into questions (questiontext) values (?)', 
            [request.form['questiontext']])

    for i in range(4): #4 choices
        g.db.execute('insert into choices (choicetext, question_id) values(?, ?)',
                [request.form['choicetext'], 4])
    g.db.commit()
    return redirect(url_for('show_polls'))

但这行不通。我不确定是我的观点有误还是 HTML 布局部分有误。有人可以帮我吗?

这是添加投票的 HTML 部分:

{% for i in range(4) %}
            <dt>Choices:
            <dd><input type=text name=choicetext>
        {% endfor %}

最佳答案

没有完整的模板或 HTML,我将假设 HTML <form>已验证。参见 HTML Forms and Inputs如果您怀疑那里有问题。

要验证表单值是否到达您的 add_poll() 函数,请尝试使用 Flask debug mode (即设置 app.debug = Trueapp.run() 之前)。要强制调用调试器,请在 add_poll() 函数中插入一个错误并从浏览器再次提交表单。应出现 Traceback 的副本。单击回溯最后一行中的“控制台”图标(这应该是您在 add_poll() 中创建的错误)并开始以交互方式检查 request.form 对象。

[console ready]
>>> request.form
werkzeug.datastructures.ImmutableMultiDict({'choicetext': u''})
>>> str(request.form)
"ImmutableMultiDict([('choicetext', u'choice1'), ('choicetext', u'choice2'), ('choicetext', u'choice3'), ('choicetext', u'choice4')])"
>>> dir(request.form)
['KeyError', '__class__', '__cmp__', '__contains__', '__copy__', '__delattr__',    '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add', 'clear', 'copy', 'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'iterlists', 'iterlistvalues', 'itervalues', 'keys', 'lists', 'listvalues', 'pop', 'popitem', 'popitemlist', 'poplist', 'setdefault',         'setlist', 'setlistdefault', 'to_dict', 'update', 'values'  ]
>>> request.form.getlist('choicetext')
[u'choice1', u'choice2', u'choice3', u'choice4']

希望这将明确 add_poll() 中必须更改的内容并简化您应用程序的 future 调试。祝你好运!

有关更多信息,请阅读 Flask.request.form 上的文档和 werkzeug.datastructures.MultiDict对象。有关在 Flask 中处理表单验证的示例(管道就位后的下一步),此 Flask pattern document on Form Validation可能是一个很好的起点。

关于python - 为 flask 投票应用程序输入选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5576005/

相关文章:

php - Gears 和 Mysql 同步

javascript - 如何将 SQLite 本地数据库连接到 HTML 前端?

python - 二维列表的排列 (Python)

python - 在 Python 中获取其他正在运行的进程窗口大小

python - ndb.get_multi(keys) 返回 None 的数组

jquery - 滚动页面时滚动 Div

html - Safari Border Radius 裁剪问题

python - HTTP 版本或 header 会影响网页的视觉外观吗?

html - 将图像附加到第一个字母

c# - SQLite Windows 10 RTM 通用应用程序