如何在表单提交后获取新对象?

时间:2015-10-20 21:16:55

标签: forms python-3.x flask jinja2

我正在尝试烧瓶,有一个简单的任务来提交表格。 页面显示一张图片和一张表格,如果表格正确提交,图片应该更改,如果没有 - 是相同的。 我无法理解如何在页面上只显示一个对象并在表单提交后获得另一个对象的机制。 试图在图像列表上使用迭代器是文件夹“静态”,但我的实现无法正常工作。 请以严谨的方式向我提供反馈意见?

现在我有一个简单的观点:

@app.route("/", methods=["GET", "POST"])
def start_view():
    picture = None
    form = InputForm(csrf_enabled=False)
    if form.validate_on_submit():
        picture = form.picture.data
        form.picture.data = ""

    return render_template('04-2.html', form=form, picture=picture)

class InputForm(Form):
    picture = StringField('What is on a picture?', validators[DataRequired()])
    submit = SubmitField('Submit')

一个简单的模板:

<body>
    <form method="POST">
    {{ form.picture.label }} {{ form.picture }}
    {{ form.submit() }}
    </form>
    {% if form.errors %}
        <span style="color: red">{{ form.error }}</span>
    {% endif %}
</body>

谢谢!

1 个答案:

答案 0 :(得分:1)

您的表单不包含任何图片。它有一个StringField和一个SubmitField。如果要查看任何图像,您需要在HTML中指向服务器中图像位置的<img>标记 您的观点应如下所示:

from Flask import session
# in order to use sessions you have to use a secret key for your app
app.secret_key = 'some secret key'
@app.route("/", methods=["GET", "POST"])
def start_view():
    img_list = ['filename1', 'filename2', 'filename3']

    # if this is not the first form submission
    if session.has_key('current'):
        # if we reach the end of the list show the first image again
        if int(session['current']) == len(img_list) - 1:
            session['current'] = 0
        # move to next image
        else:
            session['current'] = int(session['current']) + 1
    else:
        session['current'] = 0

    picture = 'first_image_filename' # this should be the img on load
    form = InputForm(csrf_enabled=False)
    if form.validate_on_submit():
        picture = img_list[int(session['current'])] # the filename of the next image
        form.picture.data = ""

    return render_template('04-2.html', form=form, picture=picture)

因此模板应如下所示:

<body>
    <form method="POST">
        {{ form.picture.label }} {{ form.picture }}
        <img src="{{url_for('static', filename='img/' + picture)}}"
        {{ form.submit() }}
    </form>
{% if form.errors %}
    <span style="color: red">{{ form.error }}</span>
{% endif %}
</body>