Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django static files not working

Tags:

python

django

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.

like image 567
Franz Payer Avatar asked Aug 20 '12 17:08

Franz Payer


1 Answers

In development:

  • STATICFILES_DIRS should have all static directories inside which all static files are resident

  • STATIC_URL should be /static/ if your files are in the local machine otherwise put the base URL here e.g. "http://example.com/"

  • INSTALLED_APPS should include 'django.contrib.staticfiles'

In the template, load the staticfiles module:

{% load staticfiles %}
..
..
<img src='{% static "images/test.png" %}' alt='img' />

In Production:

  • Add STATIC_ROOT that is used by Django to collect all static files from STATICFILES_DIRS to it

  • Collect static files

python manage.py collectstatic [--noinput]
  • add the path to urls.py
from . import settings
    ..
    ..
urlpatterns = patterns('',
..
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':settings.STATIC_ROOT)}),)`

More detailed articles are listed below:

http://blog.xjtian.com/post/52685286308/serving-static-files-in-django-more-complicated

http://agiliq.com/blog/2013/03/serving-static-files-in-django/

like image 113
Muhammad Soliman Avatar answered Oct 08 '22 09:10

Muhammad Soliman