模板
变量输出
{{ name }} # 输出变量{{ users.0 }} # 去list第一个元素{{ user_dict.k1 }} # 取dict中元素
条件/循环
{% if n == 1 %}{% elif n==2 %}{% else %}{% endif %}<ul>{% for item in users %}<li>{{ item }}</li>{% endfor %}</ul>
forloop.counter当前循环计数,从1开始forloop.counter0当前循环计数,从0开始,标准索引方式forloop.revcounter当前循环的倒数计数,从列表长度开始forloop.revcounter0当前循环的倒数计数,从列表长度减1开始forloop.firstbool值,判断是不是循环的第一个元素forloop.lastbool值,判断是不是循环的最后一个元素forloop.parentloop用在嵌套循环中,得到parent循环的引用,然后可以使用以上的参数
函数
{% for i in dic.keys %} # => dic.keys()# 模板中默认执行函数无需加括号,且不能传参数{% endfor %}
自定义函数
simple_filtersimple_tag
1. 在app中创建templatetags模块2. 创建一个xxx.py文件3. 在xxx.py------------------------------from django import templateregister = template.Library() # register 名称不能变# simple_filter 只支持最多2个参数可以作为条件语句反倒 if后面@register.filterdef my_upper(value):return value.upper()def my_add(num1, num2):return num1+num2# simple_tag 支持多个参数无法作为条件语句反倒 if后面@register.simple_tagdef my_lower(value):return value.lower@register.simple_tagdef my_join(s1,s2,s3):return s1+s2+s3@register.inclusion_tag("mb/show.html")def func(arg):# 这个数据将创给mb/show.html模板中渲染,渲染后将这个页面内容返回return {'name': 'hehe'}4. 使用 xxx.html-----------------------------------{% load xxx %} # 导入模块 xxx.py# simple_filter{{ name | my_upper }}{{ n1 | my_add:"11" }} #冒号后面不能有空格# simple_tag{% my_lower "HEHE" %}{% my_join "a" "nihao" "hehe" %}
母版
layout.html 母版文件---------------------<html>....{% block xx %}{% endblock %}...</html>~~~~~~~~~~~~~~~~~~~~~~~~~~~xxx.html 继承母版的html--------------------------------{% extends 'layout.html' %}{% block xx %}这里的内容会在模板的block名为xx的block中显示{% endblock %}
include
# 公共组件pub.html--------------------<h1>这是一个组件</h1><div>{{ name }} # index导入后,变量可以在组件中直接显示<div># 哪里需要组件代码 则直接 includeindex.html-----------------------------{% include "pub.html" %}
xss 脚本注入
Django对标签内容会自动转义,使用safe 取消转义, 使用safe要对特殊字符处理
模板中{{ content | safe }}views中from django.utils.safestring import mark_safetemp = "<a href='https://www.baidu.com'>百度</a>"newtemp = mark_safe(temp) 模板中不加safe 也会以标签输出
模板中直接显示model中的choice中的中文
get_字段名_display()
使用values 和 values_list 获取数据时无效,只能是models对象
# modles.pystatus_choice = ((1, '正常'),(2, '禁用'),)status = models.SmallIntegerFields(choices=status_choice)
{{ item.get_status_display }}status = 1 显示 正常函数 : get_字段名_display
CSRF(XSRF)跨站伪造请求
settings.pyMIDDLEWARE = [# ...,# 注释下面 则关闭CSRF功能,整个网站都不验证django.middleware.csrf.CsrfViewMiddleware,# ...,]'''xxx.html--------------------------'''<form >{% csrf_token %} ## 没有加csrf_token 会403错误# 自动生成 input 并在 cookies中也添加key为csrftoken<input type='hidden' name='csrfmiddlewaretoken' value='....' />{{ csrf_token }} # 只是csrf_token随机字符串</form>views.py------------------------from django.views.decorators.csrf import csrf_exempt, csrf_protect# 全局使用时, csrf_exempt 局部禁用# 全局禁用时, csrf_protect 局部启用# 只对下列不进行验证, 添加装饰器@csrf_exemptdef test(request):...CBV中--------------------------from django.utils.decorators import method_decorator@method_decorator(csrf_protect) # 只能加在类上,不能加在方法上class Foo(View):def get(self, request):...def post(self, request):...
ajax请求时CSRF
1. 通过获取input中csrf_token(可用 {{csrf_token}}),在data中添加 csrfmiddlewaretoken$.ajax({url: '{% url 'user_reset' form.instance.pk %}',type: 'POST',datatype: 'json',data: {'csrfmiddlewaretoken': '{{ csrf_token }}'},success: function (res) {alert(res.msg)},error: function (err) {console.log(err);alert('网络或服务器问题,重置密码失败')}})2. 通过cookie获取,请请求头中var csrf_token = $.cookie('csrftoken'); # jquery cookie 模块$.ajax({url: 'xxxx',type: 'post',headers:{'X-CSRFToken': csrf_token,}data:{}...})
CBV
urls.py---------------------------# 不同的请求方式,会执行Login类中不同的方法url(r'^login.html$', views.Login.as_view())views.py---------------------------from django.views import Viewclass Login(View):# get 查 post 创建 put 更新 delete 删除def get(self, request):# /login.html get的请求执行该方法...def post(self, request):# /login.html post的请求执行该方法......
CBV中dispatch方法
CBV中优先执行的是dispatch方法
class Login(View):def dispatch(self, request, *args, **kwargs):# 重写dispatch方法,可在该方法中对get、post等进行批量操作# ...# 调用父类的方法obj = super(Login, self).dispatch(request, **args, **kwargs)return objdef get(self, request):# /login.html get的请求执行该方法# ...def post(self, request):# /login.html post的请求执行该方法# ...# ...
CBV应用装饰器
@method_decorator(装饰器名, name=’get/post/…’)
# 1. 在类上加 name可省略,加上后制定方法名,则对改方法生效@method_decorator(装饰器名, name='get/post/...')class Foo(View):def get(slef, request):...def post(self, request):......# 2. 直接在方法上加class Foo(View):@method_decorator(装饰器名) # 只对改方法生效def get(slef, request):...def post(self, request):......
- 加
csrf_exempt的装饰器时,应加dispatch方法上 - 或加在类上
@method_decorator(csrf_exempt, name='dispatch')
FBV
urls.py---------------------------url(r'^login.html$', views.login)views.py-----------------------------def login(request):...
