Yakuzhy
Yakuzhy

Reputation: 235

How to set background image on Flask Templates?

My background-image works only for this template that has @app.route('/').

 <header class="intro-header" style="background-image: url('static/img/home.jpg')">

This works perfectly fine when:

@app.route('/')
def home():
    return render_template('post.html')

Everything works. I get this:

127.0.0.1 - - [19/Sep/2016 21:07:11] "GET /static/img/home.jpg HTTP/1.1" 304 

But when I use same template with:

@app.route('/post/')
def post():
     return render_template('post.html')

I get this:

127.0.0.1 - - [19/Sep/2016 21:15:23] "GET /post/static/img/home.jpg HTTP/1.1" 404 -                                                                          

And background-image is blank.

Upvotes: 22

Views: 63706

Answers (3)

iambradinbychuk
iambradinbychuk

Reputation: 31

4 years, 7 months too late, but anyways just in case someone needs help..

I found flask recognized my .jpg image was located in 'static', so adding 'static' like so "background-image: url('/static/img/home.jpg')", is adding an "extra" static. What worked for me, using the skeleton approach,

background-image: url('home.jpg');

Simple and bare, like a skeleton.

Upvotes: 3

Hamed Mahmoudkhani
Hamed Mahmoudkhani

Reputation: 603

This is a simple problem can solved by Flask documentation

Anyway, you should use something like this in your template:

background-image: url({{ url_for('static', filename='img/home.jpg') }})

but if you don't want to use Flask methods use :

url('/static/img/home.jpg')

or use another web server instead of flask default web server for your files like Apache and access via http://yoursite/static/img/home.jpg

Upvotes: 40

Andy
Andy

Reputation: 50550

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document - w3 CSS

This means that you need to change your url() a bit, to include the leading /.

"background-image: url('/static/img/home.jpg')"

Upvotes: 6

Related Questions