【问题标题】:Image not showing up in the browser图片未显示在浏览器中
【发布时间】:2021-07-19 11:55:45
【问题描述】:

这就是我想要做的事情。我保存在数据库中的图像将进入正确的路径。但他们没有出现在网站上。

@blogs.route("/post/new", methods=['GET', 'POST'])
def new_post():
    if ('user' in session and session['user'] == params["username"]):
        form = PostForm()
        if form.validate_on_submit():
            pic = save_picture(request.files['pic'])
            post = Post(title=form.title.data,
                        content=form.content.data, img=pic)
            db.session.add(post)
            db.session.commit()
            flash('Your post has been created!', 'success')
            image_file = url_for('static', filename = 'profile_pics/' + pic)
            return render_template('post.html',image_file=image_file)
        
        return render_template('create_post.html', title='New Post',
                               form=form)
    return "please login to the dashboard first. Dont try to enter without logging in!"


HTML 方面

<img src="{{image_file}}" alt="error"> 

【问题讨论】:

  • 那行不通..

标签: html python-3.x flask jinja2


【解决方案1】:

找到了解决方法!

我发现可以使用 python 中的 set 关键字作为变量将 post.img 存储在其中,然后在源中引用它。

{% set img_name = 'profile_pics/' + post.img %}

<img src="{{url_for('static', filename = img_name)}}" alt="error"> 

【讨论】:

    【解决方案2】:

    这将是路由函数:

    image_file = url_for('static', filename='profile_pics/' + post.img)
    return render_template('template.html', image_file=image_file)
    

    这就是它在模板中的样子:

    <img src="{{ image_file }}">
    

    问题可能是您实际上无法在 html 中包含嵌套变量,尤其是因为 jinja 可能将其解释为文字字符串

    【讨论】:

    • 我想向您展示我的代码我在哪里这样做?...我认为这是我的错误
    • @A-d-ash 在您的问题中发布代码,您可以编辑您的问题来这样做,但是您是否尝试过我在这里展示的解决方案?
    • 是的,先生,我试过了
    • @A-d-ash image_file=image_file
    • 哦,这是一个愚蠢的错误.. 但没有运气.. 它没有工作