django static files not working

Viewed 52759

For some reason, django is not serving up my static files.

I have already looked at a bunch of fixes for this problem, but I still have not found a solution.

Here is my configuration:

urls.py

urlpatterns = patterns('',
    (r'^$', index),
    (r'^ajax/$', ajax),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': path.join(path.dirname(__file__), 'static')}),
)

settings.py

STATIC_ROOT = '/home/aurora/Code/django/test/static/'
STATIC_URL = '/static/'
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

When I navigate to http://localhost:8000/static/css/default.css
I get this error: 'css/default.css' could not be found

When I navigate to http://localhost:8000/static/
I get this error: Directory indexes are not allowed here.

It looks like the static directory is getting mapped out, but the sub-directories are not.

6 Answers
STATIC_URL = '/static/' 
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

I am using the following setup: (in Apr 2021)

  • macos big sure
  • vscode
  • Ananconda 3 (for environment)

When I am trying to access my static files in Django using http://localhost:8000/static/test.txt if inside static folder a test.txt file exists.

  1. open the setting.py file in your main project folder then
  2. Paste this code inside settings.py at last:
STATIC_URL = '/static/'

# Added Manually
STATICFILES_DIRS = [
    BASE_DIR / "static",
]

Then restart VS Code.

Related