为Flask投票应用输入选项
我为我正在用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 %}
1 个回答
2
在没有完整模板或HTML的情况下,我假设这个HTML中的 <form>
是有效的。如果你觉得这里有问题,可以查看 HTML表单和输入。
为了确认表单中的值是否成功传递到你的 add_poll() 函数,可以尝试使用 Flask调试模式(也就是在 app.run()
之前设置 app.debug = True
)。为了强制启动调试器,可以在 add_poll() 函数中插入一个错误,然后在浏览器中再次提交表单。这样会出现一份错误追踪信息。点击追踪信息最后一行的“控制台”图标(应该是你在 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() 中需要改变什么,并简化你未来调试应用的过程。祝你好运!
想了解更多信息,可以阅读关于 Flask.request.form 和 werkzeug.datastructures.MultiDict 对象的文档。如果你想了解在Flask中如何处理表单验证(这是设置好基础后下一步),可以从这份 Flask表单验证模式文档 开始。