Jared Joke
Jared Joke

Reputation: 1356

Django can't find static images in templates

I've looked at pretty much all the examples here and in the documentation and it just isn't working at all

So in my settings.py file I have

STATIC_ROOT = '/mattr/static/'
STATIC_URL = '/mattr/public/'

STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',)

TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.static',)

TEMPLATE_DIRS = ('mattr/public', )

Basically everything needed to handle static files.

In urls.py I have the normal patterns for pages (templates load just fine) and have this extra line

urlpatterns += staticfiles_urlpatterns()

In views.py I have (this is for the homepage):

def home(request):
    t = get_template('index.html');
    html = t.render(RequestContext(request))
    return HttpResponse(html)

And in the template file index.html I have the line

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

And yet it never shows images. Even when I try to just go to the image file directly at http://127.0.0.1:8000/mattr/public/media/images/Mattr1.png it gives me a Page Not Found error. I was a bit confused where the path starts from but because my template page loads I figured I had the paths correct

Upvotes: 2

Views: 8166

Answers (3)

Jesramz
Jesramz

Reputation: 97

Try this in your settings.py:

import os
DIRNAME = os.path.dirname(__file__)

STATIC_ROOT = os.path.join(DIRNAME, 'static')

STATIC_URL = '/static/'

in your templates:

{{STATIC_URL}}css/etc...

You are also overwriting your TEMPLATE_CONTEXT_PROCESSORS instead do this: in your settings.py

import django.conf.global_settings as DEFAULT_SETTINGS

TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
"whatever_your_adding",
)

Upvotes: 0

Otskimanot Sqilal
Otskimanot Sqilal

Reputation: 2402

when you're talking about static files, do this :

STATIC_URL = '/static/' #or whatever you want

STATICFILES_DIRS = (
    '/path/to/static/root/directory/',
)

Don't forget the coma or django's admin won't have its css. It's done, no need to change anything in the urls.py

if you're talking about media, do this :

MEDIA_ROOT = '/media/' # or whatever you want

MEDIA_URL = '/path/to/media/root/directory'

and place this at the bottom at myproject.urls :

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

done!

Upvotes: 1

Raunak Agarwal
Raunak Agarwal

Reputation: 7238

Using '/' in front of the path denotes you are referring from root directory which I guess is not the case. Try doing this.

STATIC_ROOT = 'mattr/static/'

Upvotes: 0

Related Questions