三,模板变量及过滤器
1,模板路径总结
1),放在根目录下的templates设置
# 1,在根目录CRM创建一个templates(工用)文件夹,专门用来放置模板
# 2,设置seting.py文件里面的TEMPLATES里面的'DIRS':
'DIRS': [os.path.join(BASE_DIR, 'templates')]
2),单独放在App下的templates
# 1,创建一个新的App,把他下载到pycharm中
python manage.py startapp App名
# 2,确认seting.py文件里面的TEMPLATES里'APP_DIRS': True(允许访问app下的templates)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'student' # 把你的app名添加到这里,前提是这个app里有templates
]
2,模板变量
2.1,静态页面和动态页面区别:是否和后台,数据库有无交互(数据传输)
2.2,向前台传递数据的模板
# views下的配置
def index(request):
time = datetime.now() # 东八区时间:TIME_ZONE = 'Asia/Shanghai'
time_better = time.strftime('%Y年-%m月%d日 %H:%M:%S')
lst = [1, 2, 3, 4]
dct = {'name': 'xyb', 'age':20, 'tall':198}
def func():
return 'hello world'
return render(request, 'index.html', context={
'time': time,
'lst': lst,
'dct': dct,
'func': func
})
# templates下的html文件配置
"""
<body><!--可视化区域-->
<p>我是templates里面的p标签</p>
<p style="color: bisque">时间:{{ time }}</p>
<p style="color: black">列表的:{{ lst }}</p>
<p style="color: black">列表的第一个值:{{ lst.0 }}</p>
<p style="color: blue">字典:{{ dct }}</p>
<p style="color: blue">取字典里的name:{{ dct.name }}</p>
<p style="color: blue">取字典里的items:{{ dct.items }}</p>
<p style="color: fuchsia">函数返回值:{{ func }}</p>
</body>
"""
3,常用过滤器
# 利用过滤器直接对模板变量进行处理
"""
过滤器语法:{{ 变量名|过滤器[:字符串参数] }}
1,变量命名规则
2,冒号:前后不能有空格
3,可以链式调用eg:{{ lst|first|add:'666' }}
4,字符串参数可以通过模板传入,在视图函数里先定义好,通过context传入,在通过变量名调用
"""
# 时间过过滤器
def index(request):
time = datetime.now()
return render(request, 'index.html', context={
'time': time,
})
<p style="color: red">时间:{{ time|date:'Y年m月d日 H:i:s' }}</p>
# add过滤器
<p style="color: black">列表的第一个值:{{ lst.0|add:'666' }}</p> # 去列表的第一个值加上666
# 多个过滤器
<p style="color: black">列表的第一个值:{{ lst|first|add:'666' }}</p> # 同上
# 取值错误的过滤器
<p style="color: blue">取字典里的name:{{ dct.666|default:'取值错误' }}</p>
补充:xss(跨域脚本攻击)
1,恶意代码型(django本身就带有防御机制)
def index(request):
html = '<h2>我是安全的</h2>'
return render(request, 'index.html', context={
'html': html
})
<body>
{{ html }} # 这里django不会把你的htnl变量进行转换成html代码
</body>
<body>
{{ html|safe }} # 加一个safe过滤器能转换
</body>
2,木马型
4,静态文件的引用
4.1),统一放在项目根目录下,也可以放在App目录下
4.2),放置在根目录下
# 1,在根目录创建一个static文件
# 2,在seting里面设置
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# 3,在html文件中导入静态文件
{% load static %} # 在所有html代码前导入(使用灵活)
<link rel="stylesheet" href="{% static 'student/css/index.css' %}"> # 导入成功
拿取网页源码
拿取网页css