为 Flask 民意调查应用程序输入选择

发布于 2024-10-30 18:11:24 字数 1489 浏览 0 评论 0原文

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

I have made a database schema for a poll app I am making using Flask as follows:

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)
);

But I couldn't figure out how I should ask(in the HTML template) and insert the choices into the database. My 'show_polls' and 'add_polls' are below

    @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'))

But this doesn't work. I'm not sure whether I've got the views wrong or the HTML layout part. Can anyone help me with this please?

Here's the HTML part that adds the polls:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

维持三分热 2024-11-06 18:11:24

如果没有完整的模板或 HTML,我将假设 HTML

是有效的。如果您怀疑存在问题,请参阅 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 上的文档以及对象。有关在 Flask 中处理表单验证的示例(管道到位后的下一步),此 关于表单验证的 Flask 模式文档可能是一个不错的起点。

Without the full template or HTML, I am going to assume the HTML <form> is valid. See HTML Forms and Inputs if you suspect a problem there.

To verify that form values are reaching your add_poll() function, try using Flask debug mode (i.e. set app.debug = True prior to app.run()). To force invocation of the debugger, insert an error in the add_poll() function and submit the form again from a browser. A copy of the Traceback should appear. Click on the 'console' icon in the last line of the traceback (which should be the error you created inside add_poll()) and start interactively inspecting the request.form object.

[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']

Hopefully this will make clear what must change in add_poll() and simplify future debug of your app. Good luck!

For more information, read the documentation on Flask.request.form and werkzeug.datastructures.MultiDict objects. For an example of handling form validation within Flask (the next step after the plumbing is in place), this Flask pattern document on Form Validation might be a good place to start.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文