404 error for CSS file in Flask Application

12,181

Solution 1

Static should be on the same level as templates, not under app. Have you tried that?

Solution 2

I you want to change the route to the static asset's folder you could do:

app = Flask(__name__, static_folder='app/static')

check this here

Share:
12,181

Related videos on Youtube

Volatil3
Author by

Volatil3

A developer and a wannabe entrepreneur. More than 10 years of development experience on different platforms; Windows,Linux, Mac,Desktop/Web/Mobile. You can read further about me on my home site

Updated on June 14, 2022

Comments

  • Volatil3
    Volatil3 almost 2 years

    I am unable to find exact path of .css file in my flask app. Following is relevant code

    layout.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>An App</title>
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
        <div id="container">
            <div id="heading"><h3>App</h3></div>
            {% block content %}{% endblock %}
        </div>
    </body>
    </html>
    
    
    +app
      +static
        style.css
    +templates
    __init__.py
    forms.py
    models.py
    views.py
    db_repository
    .gitignore
    app.db
    config.py
    db_create.py
    

    The one with + sign are folders

    Update:

    I tried this in __init__.py, same result

    from flask import Flask
    from flask.ext.sqlalchemy import SQLAlchemy
    import os
    app = Flask(__name__)
    app.config.from_object('config')
    app._static_folder = os.path.abspath("static/style.css")
    print os.path.abspath(app._static_folder)
    db = SQLAlchemy(app)
    
    from app import views, models
    

    The link http://127.0.0.1:5000/static/style.css gives 404 error

  • Volatil3
    Volatil3 over 9 years
    You were right. I did not notice static one was out of app folder thus different from templates
  • Thang Nguyen
    Thang Nguyen over 7 years
    Worked for me. Thank you.