问题
This is my urls.py
import os.path
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
urlpatterns = patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': site_media }),
)
My site_media folder and style.css file is in
myProjectFolder/myApp/static/site_media/css/style.css
and in my base.html template (all my other templates extend off of this base.html template) this is what I have:
<head>
<title>{% block title %}{% endblock %}</title>
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
</head>
<body>
{% block header %}{% endblock %}
{% block content %}
<div id='header'></div>
{% endblock %}
</body>
and in my style.css, all I have is this:
#header {
display: inline;
background-color: black;
color: black;
border: 1px solid green;
}
and the CSS is not being applied to the
#header
div. Any idea why?
回答1:
The problem comes from 2 areas.
- wrong document_root variable passed
- not using template tags in html
1. Defining site_media variable in urls.py file is discouraged as it does not adhere to DRY principle. It should be held as a variable in your settings.py file so other modules may import if needed. In your settings.py file, add the following line:
import os.path
SITE_MEDIA_ROOT = os.path.join(
os.path.dirname(__file__), 'myApp/', 'static/', 'site_media' #this should be the correct path instead
)
Replace your urls.py file with this:
from myApp import settings
urlpatterns = patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': settings.SITE_MEDIA_ROOT }),
)
2.You should use django template tags to get the css file. In your base template, add this line above the head tag:
{% load static %}
Then replace:
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
with:
<link rel='stylesheet' type='text/css' href="{% static 'site_media/css/style.css' %}" />
After which it should work.
回答2:
Two options:
- You can modify a little bit your code in urls.py
in urls.py
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
to
site_media = os.path.join(
os.path.dirname(__file__), "../", "myApp", "static", 'site_media'
)
2. Remove
site_media = os.path.join(
os.path.dirname(__file__), 'site_media'
)
and add
{% load static %} at the beginning of base.html
and change
<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />
to
<link rel='stylesheet' type='text/css' href="{% static 'site_media/css/style.css' %}" />
The second method is preferable. Here is working code: https://github.com/lukaszszajkowski/s21083672
Here are links to documentation and reading: https://docs.djangoproject.com/en/dev/howto/static-files/#configuring-static-files Media files are served, static files aren't
来源:https://stackoverflow.com/questions/21083672/django-not-loading-css