django 1.3+ 静态资源的访问

说明:

       本文django的适用版本是1.3+,在1.4中测试通过.

1. setting.py中DEBUG=True时, 在setting.py中做如下设置:

import os
STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir,'webapp/static'))#设置静态资源路径为webapp/static

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = 'http://127.0.0.1:8000/static/'

 目录结构如图:


                  

对webapp/static/bottom.jpg的访问路径为:

http://127.0.0.1:8000/static/bottom.jpg

2.  setting.py中DEBUG=False时

2.1)  在setting.py中做如下设置:

import os
STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir,'webapp/static'))#设置静态资源路径为webapp/static

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = 'http://127.0.0.1:8000/static/'

2.2) 在djnews/djnews/urls.py的最后,加上以下代码 :

import djnews.setting 
if djnews.settings.DEBUG is False:
    urlpatterns += patterns('',
        url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': djnews.settings.STATIC_ROOT,'show_indexes':True
            }),
    )

 2.3)  对webapp/static/bottom.jpg的访问路径依然为:

http://127.0.0.1:8000/static/bottom.jpg

document_root指定静态资源的路径,可以是文件系统的绝对路径,也可以是在djnews.setting文件中设置的路径STATIC_ROOT;show_indexes设置为True,那么访问"http://127.0.0.1:8000/static/"这个路径时,将会列出静态资源文件夹下的所有文件和文件夹.

2.4) 在模板文件中对静态资源的访问如下:

{% load static %}
{% get_static_prefix as STATIC_PREFIX %}






<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>新闻中心</title>
    <link href="{{ STATIC_PREFIX }}





css/css.css" rel="stylesheet" type="text/css"/>
</head>
<body class="common_cool">
    <div class="lehuo_x_footer" id="frag30097">
        <div>Copyright &copy;2012 appbox </div>
    </div>
</body>
</html>

 此外还有几个访问静态资源的标签请参考官方文档关于静态资源访问的说明,参考地址:

  get_static_prefix标签

  STATIC_URL标签

猜你喜欢

转载自a564941464.iteye.com/blog/1471268