【问题标题】:inputing choices for a flask poll app为烧瓶投票应用程序输入选择
【发布时间】:2011-07-31 08:47:13
【问题描述】:

我已经为我正在使用 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 %}

【问题讨论】:

    标签: python html sqlite flask jinja2


    【解决方案1】:

    如果没有完整的模板或 HTML,我将假设 HTML &lt;form&gt; 是有效的。如果您怀疑那里有问题,请参阅HTML Forms and Inputs

    要验证表单值是否到达您的 add_poll() 函数,请尝试使用 Flask debug mode(即在 app.run() 之前设置 app.debug = True)。要强制调用调试器,请在 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() 中必须更改的内容并简化您的应用程序的未来调试。祝你好运!

    有关详细信息,请阅读有关 Flask.request.formwerkzeug.datastructures.MultiDict 对象的文档。对于在 Flask 中处理表单验证的示例(管道到位后的下一步),Flask pattern document on Form Validation 可能是一个不错的起点。

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 2012-05-27
      • 2017-04-06
      • 2021-05-18
      • 2015-09-07
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      相关资源
      最近更新 更多