问题
Here are my settings:
STATIC_ROOT = "/home/tony/Documents/mysite/mysite/"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/home/tony/Documents/mysite/mysite/static/",
)
And here I refer my stylesheet(This gives me an error):
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/reset.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/style.css" />
And the error in the log:
[06/Apr/2012 13:36:09] "GET /css/reset.css HTTP/1.1" 404 2193
[06/Apr/2012 13:36:09] "GET /css/style.css HTTP/1.1" 404 2193
How I thought I fixed it:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}static/css/reset.css" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}static/css/style.css" />
And it worked until I made another view-:
from django.shortcuts import render_to_response
from django.template import RequestContext
def test(request):
return render_to_response('test.html')
And in the template I added the {% extends 'base/base.html' %} and what do I get in the logs? this:
[06/Apr/2012 13:46:55] "GET /test/ HTTP/1.1" 200 964
[06/Apr/2012 13:46:55] "GET /test/static/css/style.css HTTP/1.1" 404 2229
[06/Apr/2012 13:46:55] "GET /test/static/css/reset.css HTTP/1.1" 404 2229
Notice the /test/? It doesn't load the css.
Any idea why?(I never had this problem with django1.3)
Thanks in advance :)
回答1:
You're not using RequestContext
to render your template, so the context processors aren't being run and therefore STATIC_URL
is empty.
回答2:
First of all, the following does not fix your problem because STATIC_URL
should contain /static/
, you don't want to write it yourself anywhere:
"{{ STATIC_URL }}static/css/reset.css"
Now, if you have {{ STATIC_URL }}
in your template but the /static/
does not show up in the templates then I think you're missing the template context processor for STATIC_URL
.
Add 'django.core.context_processors.static'
to your TEMPLATE_CONTEXT_PROCESSORS
setting. For example, like this:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.static',
)
If TEMPLATE_CONTEXT_PROCESSORS
is in your settings file already then you should add it to what's already there.
Also, note that STATIC_URL
ends in a slash so you'll need to remove the first slash after {{ STATIC_URL }}
here:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/css/reset.css" />
Lastly, your STATIC_ROOT
is most likely not what you intended. It should be:
"/home/tony/Documents/mysite/mysite/static/"
This is the location where the static files will be placed when you run the collectstatic
command. See Managing static files in the Django documentation.
来源:https://stackoverflow.com/questions/10042469/django-1-4-static-files-problems-and-dont-render-at-other-urls-of-my-project