j_noe
j_noe

Reputation: 147

Can't use static files via url_for in my Flask app

I learn Flask with YouTube tutorials. And every time (now it's my 3rd Flask series) I have the same exact problem - files from static folder don't do what they should do when I use url_for like this:.

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

I mean .js doesn't do anything, .css doesn't change elements' style, images do not appear on the page. And debugger doesn't show any errors. But when I use url_for to redirect a user to another route - it works perfectly! So I have no idea how to fix this. I use macbook, so maybe it is some problem with access to local files?

P.S. I don't show any code because it's not a typo in my code. Even if I copy-past the code from the tutors' github, I still have the same problem.

Upvotes: 1

Views: 3981

Answers (1)

Gino Mempin
Gino Mempin

Reputation: 29546

The first parameter to url_for is the endpoint name and 'static' is a special endpoint name to refer to the Static Files of your application:

Just create a folder called static in your package or next to your module and it will be available at /static on the application.

To generate URLs for static files, use the special 'static' endpoint name:

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

The file has to be stored on the filesystem as static/style.css.

So, given this:

<link ... href="{{ url_for('static', filename='styles.css') }}"> 

And assuming you create your Flask instance like this:

app = Flask(__name__)

Make sure your app file/folder structure is like this:

.
├── app.py
├── static
│   └── styles.css
└── templates
    └── app.html

If you are organizing your JS and CSS files like this:

.
├── app.py
├── static
│   ├── css
│   │   └── styles.css
│   └── js
│       └── app.js
└── templates
    └── app.html

Then you have to appropriately change the arguments to url_for like this:

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

If you named the static folder to something else (ex. "assets"), then you have to specify that new name to the static_folder parameter when creating the Flask instance.

app = Flask(__name__,
            static_folder="assets")

You can also check the Flask debugger logs that the static files are accessed correctly:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [29/Dec/2019 20:30:44] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [29/Dec/2019 20:30:44] "GET /static/css/styles.css HTTP/1.1" 200 -

Or your browser's debugger/inspection tools that it is indeed downloading the files correctly:

enter image description here

Upvotes: 1

Related Questions