Yuri Burkov
Yuri Burkov

Reputation: 141

Flask is not finding folders and files in Python

My files structure is following

> code.py

> templates

....> css

....> index.html

and my flask code is

from flask import Flask, url_for
from flask import render_template

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run()

and my HTML code is

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <header>
        <img class="resize" src="./pictures/apptek_logo.png" alt="apptek_logo">
        <nav>
            <ul class="nav-links">
                <li class="active"><a href="./index.html">Home</a></li>
                <li><a href="./contact.html">Contact</a></li>
            </ul>
            <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
            <script type="text/javascript">
                $(document).on('click', 'ul li', function(){
                    $(this).addClass('active').siblings().removeClass('active')
                })
            </script>
        </nav>
    </header>
</body>
</html>

For some reason, it's not loading CSS files, and any other html files at all. Is there anything necessary in Flask I have to do?

Upvotes: 0

Views: 217

Answers (1)

Benjamin Rowell
Benjamin Rowell

Reputation: 1411

Flask automatically looks for CSS, JS and other static files in your project root, in the directory:

/static

More details in the Flask docs here.

It's good practice to seperate your static files into subdirectories, like so:

/static/css
/static/js

In your example, place your CSS at the path:

/static/css/style.css

Then reference as so in your HTML:

<link rel="stylesheet" href="/static/css/style.css">

If you're using Jinja2 templates, you can do as described in the documentation:

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

Upvotes: 1

Related Questions