I have a Flask blueprint that contains templates and static files. The template is rendered correctly but the linked CSS file returns 404 not found. How do I serve static files that are located under a blueprint's folder?
app/
__init__.py
auth/
__init__.py
static/
style.css
templates/
index.html
auth = Blueprint('auth', __name__, template_folder='templates')
@auth.route('/')
def index():
return render_template('index.html')
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
To use static files in a Flask application, create a folder called static in your package or next to your module and it will be available at /static on the application. app.py is a basic example of Flask with template rendering.
Folder structure for a Flask app That folder contains two folders, specifically named static and templates. The static folder contains assets used by the templates, including CSS files, JavaScript files, and images.
To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() .
Tell the blueprint where its static folder is by passing static_folder
, then use url_for
to generate urls to the static
route on the blueprint. This is described in the docs.
auth = Blueprint('auth', __name__, template_folder='templates', static_folder='static')
url_for('auth.static', filename='style.css')
This solution only works if the blueprint has a url_prefix
. As per the docs:
However, if the blueprint does not have a url_prefix, it is not possible to access the blueprint’s static folder. This is because the URL would be /static in this case, and the application’s /static route takes precedence. Unlike template folders, blueprint static folders are not searched if the file does not exist in the application static folder.
In this case, one solution might be to put the stylesheet into the main static
directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With