默认值:
url(r'index/', views.index,{'name':"root"})
def index(request,name):
print(name)
return HttpResponse('ok')
命名空间:
/a/ include('app01.urls',namespace='m1')
/b/ include('app01.urls',namespace='mm1')
app01.urls
/index/ name='n1'
reverse('m1:n1')-->对应url /a/index/
命名空间补充:
from django.conf.urls import url,include
urlpatterns = [
url(r'^a/', include('app01.urls', namespace='author-polls')),
url(r'^b/', include('app01.urls', namespace='publisher-polls')),
]
app01.urls.py
from django.conf.urls import url
from app01 import views
app_name = 'app01'
urlpatterns = [
url(r'^(?P<pk>d+)/$', views.detail, name='detail')
]
app01.views.py
def detail(request, pk):
print(request.resolver_match)
return HttpResponse(pk)
以上定义带命名空间的url之后,使用name生成URL时候,应该如下:
v = reverse('author-polls:detail', kwargs={'pk':11})
{% url 'author-polls:detail' pk=12 pp=99 %}
自定义函数
simple_tag
1 app下创建templatetags目录
2 任意py文件 xxoo.py
3 创建template对象,register
from django import template
from django.utils.safestring import mark_safe
register=template.Library()
4.
@register.simple_tag
def hou(a1,a2):
return a1+a2
5. settings注册app
6.顶部{%load xxoo %}
7.使用 {% 函数名 arg1 arg2 %} 参数任意传
{% hou 2 9 %}
缺点:不能作为if条件
有点:参数任意
filter
1 app下创建templatetags目录
2 任意py文件 xxoo.py
3 创建template对象,register
from django import template
from django.utils.safestring import mark_safe
register=template.Library()
4.
@register.filter
def hou(a1,a2):
return a1+a2
5. settings注册app
6.顶部{%load xxoo %}
7.使用 {{ "参数一"|函数名:"参数二,参数三" }} 或 {{ "参数一"|函数名:数字 }} 参数任意传
{{ "maliya" | jz:"LSS" }}
缺点:参数最多两个,不能加空格
优点:能作为if条件
分页(自定义分页):
xss:
前端:{{page_str|safe}}
后台:mark_safe(page_str)
cookie
key, 键
value='', 值
max_age=None, 超时时间
expires=None, 超时时间(IE requires expires, so set it if hasn't been already.)
path='/', Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问
domain=None, Cookie生效的域名
secure=False, https传输
httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
auth装饰器
def auth(func):
def inner(request,*args,**kwargs):
v=request.COOKIES.get('username111')
if not v:
return redirect('/login/')
return func(request,*args,**kwargs)
return inner
FBV装饰
@auth
def index(request):
#获取当前已经登录的用户
v=request.COOKIES.get('username111')
return render(request,'index.html',{'current_user':v})
CBV装饰
from django import views
from django.utils.decorators import method_decorator
@method_decorator(auth,name='dispatch')
class Order(views.View):
# @method_decorator(auth)
# def dispatch(self, request, *args, **kwargs):
# return super(Order,self).dispatch(request,*args,**kwargs)
@method_decorator(auth)
def get(self,request):
v = request.COOKIES.get('username111')
return render(request, 'index.html', {'current_user': v})
def post(self,request):
v = request.COOKIES.get('username111')
return render(request, 'index.html', {'current_user': v})