0

in my settings.py I have:

import os
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
# ... #
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# ... #
STATIC_URL = '/static/'

in my urls.py I have:

urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
urlpatterns += patterns('',
    url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
        'document_root': settings.STATIC_ROOT,
    }),

)

and in my template:

<img src="{{ STATIC_URL }}images/myimage.png">

Which doesn't work. The weird thing is that if I change my settings.py:

STATIC_URL = 'static/'

and my template to:

<img src="/{{ STATIC_URL }}images/myimage.png">

does work!! I have been chasing round in circle to fix this, and I have looked at lots of forum posts, but I can't seem to figure out what I'm doing wrong.

James Khoury
  • 21,330
  • 4
  • 34
  • 65
Darwin Tech
  • 18,449
  • 38
  • 112
  • 187

1 Answers1

2

if you use staticfiles app you don't need this (assuming you are using Django 1.3):

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
    })

Its handled by the app automatically. Try to remove and see what happens.

Torsten Engelbrecht
  • 13,318
  • 4
  • 46
  • 48
  • Isn't that only for Django 1.3+? – James Khoury Aug 18 '11 at 02:34
  • Yes, but he didn't mention which Django version he is using. My guess would 1.3 though. – Torsten Engelbrecht Aug 18 '11 at 03:56
  • Its probably a good idea to put that in the answer for others who stumble upon this. – James Khoury Aug 18 '11 at 04:08
  • yes - it's 1.3. If I remove the static url pattern I get the same behaviour: http://localhost/static/images/myimage.png yields a 404. – Darwin Tech Aug 18 '11 at 05:06
  • @darwin then you need to read: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development I believe you should use `urlpatterns += staticfiles_urlpatterns()` and run `./manage.py collectstatic` – James Khoury Aug 18 '11 at 06:10
  • i have used the urlpatterns helper and still the same. Running ./manage.py collectstatic will just place files into the static folder. Something already there should still be able to be served. – Darwin Tech Aug 18 '11 at 08:29
  • @darwin did you read https://docs.djangoproject.com/en/dev/howto/static-files/#basic-usage by any chance. I think it refers to having `static/` folder in your apps. – James Khoury Aug 18 '11 at 10:39
  • 1
    ok. Figured it out. The crucial part seems to be putting the files in a /static folder in the **apps** directory and not the **project** directory. I had been over the official documentation numerous times but had overlooked this seemingly small detail. Thanks James Khoury for making me take another look. – Darwin Tech Aug 18 '11 at 14:42