2

I have the following project structure:

myproject
    - myapp
    - manage.py
    - myproject
          - settings.py
          - urls.py
          ...
    - static
    - templates

I want to serve all my static files from within this static folder. In my settings.py, I have the following:

STATIC_URL = '/static/'

However, in one of my templates, when I call static files using the following...

{% load static %}
...
<link href="{% static 'css/styles.css' %}" rel="stylesheet" />

...nothing gets loaded.

However, if I add the css file within myapp/static/css/styles.css, then everything works properly. How can I serve static files from my project root folder? Thanks for any help.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
darkhorse
  • 8,192
  • 21
  • 72
  • 148
  • I'm unsure I understand your question, because in the code example it looks like you're trying to load the file from myproject/static/css/styles.css and in the last paragraph you mention that adding the css file in the said location works. Did I understand that correctly and from where would you like to serve static files? – Armin Dec 29 '19 at 12:53
  • Can you share the following settings? `STATICFILES_DIRS`, `STATICFILES_FINDERS` and `STATIC_ROOT` – Iain Shelvington Dec 29 '19 at 13:00
  • Are you working on a development server? There is an extensive explanation in this SO [link](https://stackoverflow.com/questions/9181047/django-static-files-development) – Chris Dec 29 '19 at 13:25

2 Answers2

5

First Step: Your project structure(folder directory) seems to be ok.

myproject
- myapp
- manage.py
- myproject
      - settings.py
      - urls.py
      ...
- static
- templates

Second: Need to define the STATIC_URL = '/static/' in settings.py file.

Third: Need to load the static in the template file and use the relative path.

{% load static %}
...
<link href="{% static 'css/styles.css' %}" rel="stylesheet" />

Add this settings.py file.

# Add static file directory
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

Installed Apps listing in settings.py is supposed to exist in the django.contrib.staticfiles in the list. if not then make sure its in the list.

Iqbal Hussain
  • 1,077
  • 1
  • 4
  • 12
  • This works for me, I also needed to serve static files from the root directory of my project. Just a tiny addition to above answer, make sure you import os package that is being used on the STATICFILES_DIRS tuple. – yaach May 20 '22 at 14:09
0

You should add STATICFILES_DIRS to settings.py as shown below to serve static files from Django project root directory:

# "settings.py"

STATIC_URL = '/static/'

STATICFILES_DIRS = [ # Here
    BASE_DIR / 'static/'
]
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129