Django基础,Day9 - 静态文件目录与路径设置说明(eg. images, JavaScript, CSS)

静态文件路径设置官方说明

1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.

2. In your settings file, define STATIC_URL, for example:   

1
STATIC_URL  =  '/static/'

3. Store your static files in a folder called static in your app. For example my_app/static/my_app/myimage.jpg.

4. In your templates, either hardcode the url like /static/my_app/myexample.jpg or, preferably, use the static template tag to build the URL for the given relative path by using the configured STATICFILES_STORAGE storage (this makes it much easier when you want to switch to a content delivery network (CDN) for serving static files).

1
2
3
{ %  load staticfiles  % }
 
<img src = "{% static " my_app / myexample.jpg " %}"  alt = "My image" / >
 使用实例

在前面的例子中,我们使用了上面第三种设置方式,在app目录下,创建了static目录,里面还创建了名字跟app名称一样的目录,里面才放静态资源文件,路径如:

polls/static/polls/style.css,在template中引入时使用

1
2
3
{ %  load static  % }
 
<link rel = "stylesheet"  type = "text/css"  href = "{% static 'polls/style.css' %}"  / >

一、Django 项目默认读取静态文件目录如 /projectName/appName/static/

二、如果我们不想将静态文件放到app甚至project目录下时,可以在settings.py 中设置 STATICFILES_DIRS ,如:

1
2
3
4
5
STATICFILES_DIRS  =  (
     'D://static/' ,
     # os.path.join(BASE_DIR, "static"),
     # '/var/www/static/',
)

接着前面的例子,此时创建 D://static/polls/style.css

1
2
3
4
5
6
7
li a {
     color red ;
}
 
body {
     background white  url ( "images/background.jpg" no-repeat  center  Top;
}

刷新页面 则可发现,链接中的文字颜色由原先的绿色变成了红色,说明页面引用的css路径生效

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值