Home > Enterprise >  Django Website does not load static files
Django Website does not load static files

Time:12-09

I am in the middle of creating a django project and I have templates and static folders within the project directory. I can render and view the html files however it cannot load css files stored in the static folder. I have placed the load static tag in my html file but when I run python manage.py runserver it I get this error

Performing system checks...

Watching for file changes with StatReloader
System check identified some issues:

WARNINGS:
?: (staticfiles.W004) The directory '/static' in the STATICFILES_DIRS setting does not exist.

System check identified 1 issue (0 silenced).
December 08, 2022 - 14:54:53
Django version 4.1.3, using settings 'brighterstrat.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

This is how I have referenced the static files in my html file

<link rel="stylesheet" href="{% static 'css/bootstrap.min.css'%}">
<link rel="stylesheet" href="{% static 'css/style.css'%}">

setting.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static')]
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"

How can I make it load the css files

CodePudding user response:

Django statics can be confusing, mostly because the behavior is different between prod and development (i.e DEBUG=True)

To recap the settings:

# Url at which static files are served
# It's the url the browser will fetch to get the static files
# It's prepend to static name by the {% static %} templatetag
STATIC_URL = "static/"

# Directory where static files can be found
# When DEBUG = True, static files will be directly served from there by 
# the manage.py runserver command
STATICFILES_DIRS = [BASE_DIR / "static"]

# Directory to export staticfiles for production
# All files from all STATICFILES_DIRS will be copied by 
# manage.py collectstatic to this directory.
# /!\ It will not be served by django, you have to setup 
# your webserver (or use a third party module) 
# to serve assets from there.
STATIC_ROOT = BASE_DIR / "assets"

In you example, it seems you didn't place your files in a directory listed by STATICFILES_DIRS so make sure you have those files:

| manage.py (root of your django app)
| static
|   |- css
|   |   |- bootstrap.min.css
|   |   |- style.css

CodePudding user response:

To debug this, you can add a print in your settings:

print([os.path.join(BASE_DIR, '/static')])

To fix this, you just have to remove the slash for it to work correctly.

From the os.path.join() docs:

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

That's why BASE_DIR is being cut off.

  • Related