django 加载静态文件

在使用Django开发的Web项目中是避免不了使用css、javascript、js等静态文件的,而对于这些静态文件的处理,django官 网这样写:Django itself doesn’t serve static (media) files, such as images, style sheets, or video. It leaves that job to whichever Web server you choose.就是说django本身不处理类似于图片、样式表、视频等静态文件,它将此项工作交给了你选择的Web服务器。
在网上搜索到的django项目处理静态文件的示例中,大家似乎都在使用如下的方法让django处理静态文件:
Python代码
urlpatterns += patterns(”,
(r’^static/(?P.*)$’, ‘django.views.static.serve’,
{‘document_root’: settings.MEDIA_ROOT}),
)

而对于django.views.static.serve方法,django官网说得很清楚:Using this method is inefficient and insecure . Do not use this in a production setting. Use this only for development.就是说这种方法是低效且不安全的,不要在生产环境使用此方法,只在开发环境使用。
这时对于静态文件的处理,我们只能使用我们选择的Web服务器来处理了。比如使用nginx服务器的话,可以如下设置:
先设置settings.py,如下,
Python代码
MEDIA_ROOT = ‘/home/denghaiping/workspace/djcode/mysite/static/’

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: “http://media.lawrence.com/media/”, “http://example.com/media/”
MEDIA_URL = ‘/static/’

# Absolute path to the directory static files should be collected to.
# Don’t put anything in this directory yourself; store your static files
# in apps’ “static/” subdirectories and in STATICFILES_DIRS.
# Example: “/home/media/media.lawrence.com/static/”
STATIC_ROOT = ”

# URL prefix for static files.
# Example: “http://media.lawrence.com/static/”
STATIC_URL = ‘/static/’

# URL prefix for admin static files — CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: “http://foo.com/static/admin/”, “/static/admin/”.
ADMIN_MEDIA_PREFIX = ‘/static/admin/’

apache2 配置如下:
Python代码

SetHandler None
Order allow,deny
Allow from all

Alias /static /home/denghaiping/workspace/djcode/mysite/static
Alias /static/admin /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media


SetHandler None
Order allow,deny
Allow from all


如此配置以后,就可以让web服务器来高效的处理静态文件,而让django来处理动态内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值