我正在尝试使用我的CSS,图像和javascript加载到我的Django模板中
{{ STATIC_URL }}
我遇到问题让它运转起来。以下是相关代码:
Url's.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
...
urlpatterns += staticfiles_urlpatterns()
Settings.py
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_URL = '/assets/'
STATIC_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, 'static'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/Users/Chris/project/static/",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
样式表URl:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css">
如果您需要更多信息,请询问,并感谢您的帮助!
更新: 我添加了以下尝试解决问题的方法。但它仍然存在:
到我试图导入样式表的视图:
'context_instance':RequestContext(request),
到setting.py文件:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
)
如果这有帮助,这是我的已安装应用程序:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'djblog',
)
管理员的我的URLs.py文件,并指向我的其他网址文件:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'blog.views.home', name='home'),
# url(r'^blog/', include('blog.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'^', include('djblog.urls')),
)
我的主要网址文件:
from django.conf.urls.defaults import *
from views import *
from models import *
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
(r'^$', list),
(r'^archive/(?P<archive>\d{1,2})/$', list),
(r'^\d{4}/\d{1,2}/(?P<sl>.*)/$', detail),
(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/$', month),
(r'^(?P<year>\d{4})/$', year),
(r'^category/$', category),
(r'^category/(?P<category>.*)/$', one_category),
(r'^tag/$', tag),
(r'^tag/(?P<tag>.*)/$', one_tag),
)
urlpatterns += staticfiles_urlpatterns()
答案 0 :(得分:0)
我已经解决了我自己的问题。在Kay Zhu
的帮助下在我的视图中,我将“context_instance”关键字参数传递给render_to_response,这是错误的。
以下是context_instance正确用法的示例:
def one_tag(request, tag):
#http://site_name/tag/tag_name
posts = Post.objects.order_by('-published').filter(tags__name=tag.lower())
return render_to_response('blog/one_tag.html',
{'posts':posts, 'tag':tag,},
context_instance=RequestContext(request))
这也可以解决您的类似问题。使用以下代码将文件添加到程序目录:
def media_url(request):
from django.conf import settings
return {'media_url': settings.MEDIA_URL}
这篇博文有很多好消息:http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/ 要小心,它来自2006年:)