Django静态资源URL STATIC_ROOT的配置方法
生活中的经济学 txt,张木易个人资料,葡萄沟教案
缘由
新手学习 django 当配置好 html 页面后,就需要使用一些静态资源,如图片,js 文件,css 样式等,但是 django 里面使用这些资源并不是直接引用一下就好,还要配置路径即 static_url 如果这个配置不好的话,请求这些静态资源将返回 http 404 。
经验传授
1. 输出 settings.py 文件里面的 static_url 到html页面,看一下物理路径指向了哪些,通常是不是跑出根目录的。这里给个demo:
def home(request):
t = get_template("")
html = t.render(context({
"template_dir":settings.template_dirs[0],
"title":"home",
"static_dir":settings.static_root}))
return httpresponse(html)
这样访问的html页面就可以看到这些路径了。
2. 配置 static_root 变量
static_root = os.path.join(os.path.dirname(__file__), '..', 'templates/content').replace('\\','/')
可能通过调整第二个和第三个参数来将路径修改正确。(多调试)
3. 在 urls.py 文件中配置 urlpatterns 变量(主要看高亮这一行):
urlpatterns = patterns('',
url(r'^$', home),
url(r'^static/(?p<path>.*)$','django.views.static.serve',{'document_root':settings.static_root}),
)
4. 测试以上配置:
<head>
<meta charset="utf-8"/>
<title>{{ title }} - oger</title>
<script type="text/javascript" src="/static/scripts/jquery-1.11.0.min.js"></script>
</head>
或
<head>
<meta charset="utf-8"/>
<title>{{ title }} - oger</title>
{% load staticfiles %}
<script type="text/javascript" src="{% static 'scripts/jquery-1.11.0.min.js' %}"></script>
</head>
[/code]
这两种用法都是可以的。
用 django 开发web站点还是很方便的。继续学习中...
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
python如何查看网页代码
用python查看网页代码的方法:1、使用“import”导入requests包import requests2、使用requests包的get()函数通过网页...
[阅读全文]
-
-
python如何保存文本文件
python保存文本文件的方法:使用python内置的open()类可以打开文本文件,向文件里面写入数据可以用write()函数,写完之后,使用close()函...
[阅读全文]
-
python如何编写win程序
python可以编写win程序。win程序的格式是exe,下面我们就来看一下使用python编写exe程序的方法。编写好python程序后py2exe模块即可将...
[阅读全文]
-
-
-
-
-
-
网友评论