十、Django静态文件
django网络相应基础:
1、配置url路由
在urls.py中 urlpatterns添加路径
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index.html$', views.index),
url(r'^ajax1.html$', views.ajax1),
url(r'^upload.html$', views.upload),
url(r'^upload_img.html$', views.upload_img),
url(r'^jsonp.html$', views.jsonp),
url(r'^ajax3.html$', views.ajax3),
]
2、定义视图函数
在应用文件夹的views.py中,添加函数,响应urls.py路由
from django.shortcuts import render,HttpResponse
def index(request):
return render(request,'index.html')
def ajax1(requset):
return HttpResponse('OK')
...
3、创建html模版
在模版目录下(默认templates文件夹)创建index.html等模版
模版路径配置:setting.py中的TEMPLATES -> DIRS参数
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
4、给模版传入参数
def upload(request):
import time
t = time.ctime()
return render(request,'upload.html', {"time":t})
def upload(request):
import time
t = time.ctime()
return render(request,'upload.html', locals())
locals() : 自定义变量t、request等局部变量都传给模版
5、模版使用参数
<body>
<div>
<h1>{{ time }}</h1>
...
6、statics目录
在项目中创建statics目录用于存放js、css等静态文件
需要在项目配置中声明静态文件路径
STATIC_URL = '/static/' #静态文件路径的别名,在模版中使用
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'statics'), #配置静态文件的绝对路径
os.path.join(BASE_DIR, 'app01','statics'), #如果有根目录/app01/statics时声明,或os.path.join(BASE_DIR, 'app01/statics'),
)
7、模版中引入静态文件
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css"/>
<link rel="stylesheet" href="/static/plugins/font-awesome/css/font-awesome.css"/>
<link rel="stylesheet" href="/static/css/edmure.css"/>
<link rel="stylesheet" href="/static/css/commons.css"/>
<link rel="stylesheet" href="/static/css/row-avatar.css"/>
<script type="text/javascript" src="/static/js/jquery-1.12.4.js"></script>
<script type="text/javascript" src="/static/plugins/bootstrap/js/bootstrap.js"></script>
</head>
<body>
...
或使用 {% load staticfiles %}声明 然后引入时
路径 = “{% static '静态文件在statics目录下的路径’ %}"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% load staticfiles %}
<title>Title</title>
</head>
<body>
<h1>Hello {{ name }}{{ t }} {{ request.method }}</h1>
{#<script src="/static/jquery-3.1.1.js"></script>#}
<script src="{% static 'jquery-3.1.1.js' %}"></script>
<script>
$("h1").css("color","red")
</script>
</body>
</html>
这种方式生效的前提:(setting.py)django.contrib.staticfiles已经添加到settings.INSTALLED_APPS中, 而STATIC_URL也设置了。