【问题标题】:how is it possible to show form data and uploaded image to a page in flask如何将表单数据和上传的图像显示到烧瓶中的页面
【发布时间】:2015-10-21 19:03:10
【问题描述】:

如何将表单数据和上传的图像显示到页面。就像它是一个学生申请网站,学生将在其中填写他的信息以及他的照片。因此,当他提交时,他将被重定向到另一个页面“apply.html”,其中填写了他自己的信息并在页面上显示了一张图片,有点像录取卡。

我能够将图像上传到我的“静态/上传”文件夹,并且当提交表单时,用户会被重定向到“apply.html”并填写信息,但我找不到在“上显示图像的方法”应用.html"

这是我的代码

@app.route('/form.html', methods=['GET', 'POST'])
def form():
  nform = NewRegistration(request.form)
  if request.method == 'POST':
    if nform.validate() == False:
      flash('All fields are required.')
      return render_template('form.html', form=nform)
    else:

        try:
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        except Exception as e:
            print "Form without file "+e
        post = request.form['element_15'].strip()
        name = request.form['element_1_1'].strip()
        last = request.form['element_1_2'].strip()
        Name = str(name)+ ' ' +str(last)
        father = request.form['element_2'].strip()
        mother = request.form['element_3'].strip()
        gender = request.form['element_17'].strip()
        data = {'Name' : Name, 'post' : post, 'father' : father}
        return render_template("apply.html", data=data)

    elif request.method == 'GET':
      return render_template('form.html', form=nform)

【问题讨论】:

    标签: flask flask-wtforms flask-login


    【解决方案1】:

    在您的apply.html 模板中,您可以有一个<img> 标记指向您上传的图像。考虑将图像保存在 img 文件夹下的 static 文件夹中。然后你可以使用:

    <img src="{{url_for('static', filename='img/' + filename)}}">
    

    为了使用文件名,在表单视图返回语句中添加一个文件名变量:

    return render_template("apply.html", data=data, filename=filename)
    

    【讨论】:

    • 我在 apply.html 中有图像标签,但我没有得到将逻辑放在 routes.py 上。
    • 它有点工作,它显示了正确的图像名称,但未能正确加载。
    • 好吧,对不起,脑子太累了,连简单的逻辑都想不出来。做过。谢谢你
    • UPLOAD_FOLDER 在您的配置中设置为 /static/img??
    • 我只需要这样做 。我完成了,它起作用了。谢谢你的时间。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2019-01-11
    • 2021-03-18
    • 2021-07-03
    相关资源
    最近更新 更多