Search code examples
htmlcssdjangodjango-staticfilesstatic-files

Django Global Static Files Not Found


I'm trying to create/use a global css file for my project, it seems to be resolving to the correct location, but it's still not finding the file.

The relevant section of my settings.py file is:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'abcdefg')
STATIC_URL = '/static/'
STATICFILES_DIR = [
     os.path.join(BASE_DIR, 'static')
]

and I have django.contrib.staticfiles in my installed apps.

My file structure is:

Project/
├── abcdefg/
│   ├── admin/
│   ├── App/
├── Project/
│   ├── __init__.py
│   ├── settings/
│   ├── urls.py
│   └── wsgi.py
├── App/
│   └── static
│       └── App
│           └── css
│               └── test.css
│   └── __init__.py
│   └── admin.py
│   └── apps.py
│   └── models.py
│   └── views.py
│
├── manage.py
│
├── static/
│   └── base
|       └── css
|           └── test.css
└── templates/
    └── base.html

My base.html simply looks like this:

{% load static %}

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="{% static 'base/css/global.css' %}">
  <title>Title {% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
  <h1>Test</h1>
{% endblock %}
</body>
</html>

When I try to access the page I get the following error: [08/Feb/2020 11:26:50] "GET /static/base/css/test.css HTTP/1.1" 404 1683 which indicates that it's pointing to the correct location but it's not actually grabbing the file. If I change the link href in base.html to {% static 'App/css/test.css %} everything works as expected.

I added a location that the STATIC_ROOT maps to and ran python manage.py collectstatic to no avail.

I'm assuming there's something stupid that I'm overlooking in the docs, but I essentially followed this video to a T and I'm not getting the global file to import.

I've added all relevant files to GitHub at https://github.com/JVP3122/django_help so that I'm not just showing a little bit of code. Also, this is not the official repo for my project so it does not matter that the django secret is visible.


Solution

  • It should be STATICFILES_DIRS rather than STATICFILES_DIR. Also, it was better to have STATIC_ROOT set to a different folder so it doesn't overwrite the global static files. You'd need to create a folder called 'static_files' in the main project directory, and change these 2 lines:

    STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
    STATICFILES_DIRS = [
        ('global', os.path.join(BASE_DIR, 'static')),
    ]
    

    Then you will be able to load the global file at: {% static 'global/base/css/test.css' %}