其他分享
首页 > 其他分享> > django-static配置静态文件

django-static配置静态文件

作者:互联网

配置静态文件

staitic_url 、 static_root 、 STATICFILES_DIR的区别

static加载





views.py

from django.http import HttpResponse
from django.shortcuts import render

def showimg(request):
    return render(request,'test_static.html')

setting.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

"""有些静态文件不是某个app独有,需要建立一个公共的静态文件的文件夹,如何让django知道你把一些静态文件放到app以外的公共文件夹中呢,那就需要配STATICFILES_DIR了
STATICFILES_DIRS告诉django,首先到STATICFILES_DIRS里面寻找静态文件,其次再到各个app的static文件夹里面找。
"""
STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'),
)

test_static.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test_static</title>
</head>
<body>
    <h5>绝对路径</h5>
    <img src="http://127.0.0.1:8000/static/img2.jpg" width='200',heligth='200'>
    <h5>相对路径</h5>
    <img src="/static/img2.jpg" >
    <h5>load加载引用</h5>
    {% load static %}
    <img src="{% static 'img2.jpg'%}" >
    <!--static标签更动态-,静态文件头的请求头变化,
        当setting:STATIC_URL = '/statics/'修改后,static路径自动发生变化  -->
</body>
</html>

显示页面html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test_static</title>
</head>
<body>
    <h5>绝对路径</h5>
    <img src="http://127.0.0.1:8000/static/img2.jpg" width='200',heligth='200'>
    <h5>相对路径</h5>
    <img src="/static/img2.jpg" >
    <h5>load加载引用</h5>
    
    <img src="/static/img2.jpg" >
</body>
</html>

标签:文件,静态,django,STATICFILES,static,test
来源: https://www.cnblogs.com/yescarf/p/15101903.html