Django使用静态文件

在django1.3中,提供了django.contrib.staticfiles这个模块,方便使用静态文件,显示图片,使用css,js等。
在设置时需要注意的是:
1.MEDIA_ROOT  MEDIA_URL
2.STATIC_ROOT STATIC_URL
3.ADMIN_MEDIA_ROOT
4.STATICFILES_DIRS

In settings.py:
HERE=os.path.dirname(os.path.dirname(__file__)
MEDIA_ROOT=os.path.join( HERE , 'media').replace('\\','/')
MEDIA_URL = '/media/'
STATIC_ROOT =os.path.join( HERE , 'static').replace('\\','/')
STATIC_URL= '/static/'
ADMIN_MEDIA_ROOT = '/static/admin/'
STATICFILES_DIRS = (
       os.path.join(HERE,'app1/static/').replace('\\','/'),
       os.path.join(HERE,'app2/static/').replace('\\','/')
)

In urls.py add these codes:
from django.conf import settings
from djagno.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT )
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT )

in templates:
{% load static %}
<img src="{{ get_static_prefix }}images/1.jpg" />
<link href="{get_static_prefix}}css/truple.css />

很重要的几段话:
1.# Don't put anything in this directory(STATIC_ROOT) yourself; store your static files  in apps' "static/" subdirectories and in STATICFILES_DIRS.

2.The most likely example is user-uploaded content in MEDIA_ROOT. staticfiles is intended for static assets and has no built-in handling for user-uploaded files, but you can have Django serve your MEDIA_ROOT by appending something like this to your URLconf:
     urlpatterns += static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT )

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值