django2.0 中如何显示静态文件(图片、css 和js )

参考了几个博客,然后总结了一下,有误请指正。

 

这是我相关文件的路径

 

1.在settings.py 文件的末尾加上加上以下代码:

STATIC_URL = '/static/'
HERE = os.path.dirname(os.path.abspath(__file__))
HERE = os.path.join(HERE, '../')
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(HERE, 'static/'),
)

    STATIC_URL = ' / static / '      :   static 是在项目中建立的用来存放静态文件的文件夹

    HERE = os.path.dirname(os.path.abspath(__file__))    :   这是在给HERE赋web的绝对路径

    STATICFILES_DIRS = (

        os.path.join(HERE, 'static/'),

    )  

    这是设置静态文件的公共路径  (实际上这些就是路径的翻来覆去,理清楚理清楚就好了)

 

2.在urls.py 文件中添加以下代码:

from . import settings
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATICFILES_DIRS)
# 这个加在末尾,注意,是末尾,urlpatterns 括号外

    这里相当于urlpatterns += static(/static/, document_root=settings.STATICFILES_DIRS)

    意思是/static/ 等效于settings.STATICFILES_DIRS 的路径,其他地方调用/static/ 相当于调用settings.STATICFILES_DIRS

 

    在py中调用绝对路径:

'%s\\img/brain2.jpg' % settings.STATICFILES_DIRS

 

 

3.最后在http或者css文件中加上相应的图片链接就行了,比如我这个是css文件中加上背景图片:

background: url("/static/img/1.jpg");

4.css 加在html 上同理:

<link rel="stylesheet" href="/static/css/style.css" />

(js 跟css 差不多,这里就不写了)

 

萌新博客,仅供参考,如有错请指出,感激不尽

 

借鉴博客:https://blog.csdn.net/xxx_gt/article/details/79719790

                  https://www.cnblogs.com/zhouxihi/p/7398376.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值