darkhorse
darkhorse

Reputation: 8722

Serving static files from the project directory in Django

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.

Upvotes: 2

Views: 3609

Answers (2)

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/'
]

Upvotes: 0

Iqbal Hussain
Iqbal Hussain

Reputation: 1105

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.

Upvotes: 5

Related Questions