Flask does not load css file with query string

Question:

I have started to work on flask, and the problem is i have created a css file in static folder and wanted to load that css file on template.

but it is not loading css file even if i try this on incognito mode i thought it could be a cache problem but it does not.

<!DOCTYPE html>
<title> Welcome to My Blog</title>

<link rel="stylesheet" type="=text/css" href="{{ url_for('static', filename='style.css?v=0.01') }}">

<h2>Hey there {{ name }}</h2> 

Image :Hello world flask app

Blog.py

from flask import Flask, request, render_template

app = Flask(__name__)


...
@app.route('/profile/<username>')
def profile(username):
    return render_template("profile.html", name=username)

...

if __name__ == '__main__':
    app.run(debug=True, port=8080)

style.css

h2{
    color: #00bfff;
}
Asked By: burc

||

Answers:

The problem is that you include the query string in your filename.

url_for('static', filename='style.css?v=0.01')

The url path results in static/style.css%3Fv%3D0.01, because the special characters get encoded. To fix this you must add query elements as keyword arguments:

url_for('static', filename='style.css', v=0.01)

Additionally:

  • Your file is called stye.css and not style.css
  • Your <link> tag says type="=text/css" and not type="text/css" as it should
Answered By: vallentin

Adding to the accepted answer, Sometimes encoding itself causes the problems. Make sure you have right encoding.

<meta charset="UTF-8">

Include charset attribute in your HTML file. Also, to avoid using cached responses of your browser, try refreshing your content using ctrl + F5 keys.

Answered By: Raviteja Ainampudi

In my case I have added following line to my code and it worked

app.static_folder = 'static'

and you have to change the

<link rel="stylesheet" type="=text/css" href="{{ url_for('static', filename='style.css?v=0.01') }}">

to

<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"/>

Answered By: yashod perera
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.