烧瓶WTF表格

时间:2016-12-14 07:13:23

标签: python forms flask

我有以下功能,只从数据库中选择数据并将其分配给变量。

@app.route("/tasks")
@login_required
def tasks():
    g.db = connect_db()
    data = g.db.execute("""
            SELECT name, due_date, priority, task_id
            FROM tasks where status = 1
        """)
    open_tasks = [dict(name=row[0], due_date=row[1], priority=row[2], task_id=row[3])
                  for row in data.fetchall()]

    data = g.db.execute("""
            SELECT name, due_date, priority, task_id
            FROM tasks where status = 0
        """)
    closed_tasks = [dict(name=row[0], due_date=row[1], priority=row[2], task_id=row[3])
                  for row in data.fetchall()]
    g.db.close()
    return render_template(
        'tasks.html',
        form=AddTaskForm(request.form),
        open_tasks=open_tasks,
        closed_tasks=closed_tasks
    )

但我无法理解的是form=AddTaskForm(request.form)task.html已经是一个表单,您可以在此处看到:

<div class="add_task">
    <h3>Add a new task</h3>
    <form action="{{ url_for('add_task') }}" method="post">
        <p>
            <label>Task Name: </label>
            <input type="text" name="name">
        </p>
        <p>
            <label>Due Date: </label>
            <input type="text" name="due_date">
        </p>
        <p>
            <label>Priority</label>
            <select name="priority">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
            </select>
        </p>
        <p>
            <input type="submit" value="Save">
        </p>
    </form>
</div>

那么为什么(本教程的作者)将其分配给AddTaskForm(request.form)

forms.py来自AddTaskForm的代码如下:

from flask_wtf import Form
from wtforms import StringField, DateField, IntegerField, SelectField
from wtforms.validators import DataRequired

class AddTaskForm(Form):
    task_id = IntegerField()
    name = StringField("Task Name", validators=[DataRequired()])
    due_date = DateField(
        "Due Date",
        validators = [DataRequired()],
        format = '%m/%d/%y'
    )
    priority = SelectField(
        'Priority',
        validators = [DataRequired()],
        choices = [
            ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'),
            ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10')
        ]
    )
    status = IntegerField('Status')

1 个答案:

答案 0 :(得分:0)

很好的问题,因为表单及其动作从未在您的函数/路由/方法中使用。那么如果你在哪里使用表单来创建一个Task: 你会:

# Initialization etc.
form = AddTaskForm(request.form)
if form.validate_on_submit():
    # Do whatever with the submited data
return render_template("task.html", form=form, ...)

所以基本上你可以用同样的方法渲染结果并接受Form-Data