Django can't find static images in templates

我与影子孤独终老i 提交于 2019-12-08 00:42:32

问题


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


回答1:


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!




回答2:


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



回答3:


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",
)


来源:https://stackoverflow.com/questions/13407383/django-cant-find-static-images-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!