Flask not detecting CSS file within 'static' folder

23 Views Asked by At

I've been trying to run a Flask program, however it is not detecting the style.css file within the static folder. The organization of my different directories are shown in this image here:

file directories

My app.py code is:

from flask import Flask, render_template, request
import os
import joblib

template_dir = os.path.abspath('../templates')
app = Flask(__name__, template_folder=template_dir, static_folder='static')

and my index.html file contains:

<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/style.css') }}">
    <title>App Title</title>
</head>

I have tried different variations to make my Flask app recognize my CSS file, however none have worked. One of the methods I encountered online and tried is adding: app.static_url_path = '/static' to my app.py file, however it still results in an error. More specifically, here is my terminal response:

 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 652-831-486
127.0.0.1 - - [16/Dec/2023 13:23:07] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [16/Dec/2023 13:23:07] "GET /static/styles/style.css HTTP/1.1" 404 -

If anyone has any insight, I would really appreciate it.

2

There are 2 best solutions below

0
Dave W. Smith On BEST ANSWER

Your directory layout is non-standard. Move app.py up a level. You shouldn't need ../ anywhere.

0
e3ham On

Just figured it out. For anyone who may be running into the same issue, I modified my code in the app.py to:

template_dir = os.path.abspath('../templates')
static_dir = os.path.abspath('../static')
app = Flask(__name__, template_folder=template_dir, static_folder=static_dir)