Django请求的相关信息,cookie及其装饰器,母版继承分页,分页
- 请求的相关信息
- cookie装饰器
- 母版继承
- 自定义函数
- cookie
- session(下回分析)
- 分页
- form验证(下回分析)
Views
-请求的其他信息
def index(request,name):
print(name)
print(type(request))
#封装了所有用户请求信息
print(request.environ)
for k,v in request.environ.items():
print(k,v)
print(request.environ['HTTP_USER_AGENT'])
return HttpResponse(name)
装饰器
FBV:
def auth(func):
def inner(reqeust,*args,**kwargs):
v = reqeust.COOKIES.get('username111')
if not v:
return redirect('/login/')
return func(reqeust, *args,**kwargs)
return inner
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,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
def post(self,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
Models
一大波操作,留待后续
Templates
1,母版.html
引用母版网页 master.html
引入部分页面设置 tag.html
extends
include
实例应用
母版:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="/static/commons.css">
<style>
.pg-header{
height: 50px;
background-color: seashell;
color: green;
}
</style>
{% block css %} {% endblock %}
</head>
<body>
<div class="pg-header">小男孩管理</div>
{% block content %}
{% endblock %}
<div class="pg-footer">
</div>
<script src="/static/jquery.js"></script>
{% block js %}
{% endblock %}
</body>
</html>
继承母板:tpl1.html
{% extends 'master.html' %}
{% block content %}
<h1>用户管理</h1>
<ul>
{% for i in u %}
<li>{{ i }}</li>
{% endfor %}
</ul>
{% for i in u %}
{% include 'tag.html' %}
{% endfor %}
{% endblock %}
{% block css %}
<style>
body{
background-color: red;
}
</style>
{% endblock %}
{% block js %}
<script></script>
{% endblock %}
2,自定义函数(只在模板里有)
模板
simple_tag
a,app下创建templatetags目录
b,任意xxoo.pu文件
c,创建template对象 register
d,@register.simple_tag
def func(a1,a2,..):
return "baobaohui"
e,settings 中注册 APP
f,顶部{% load xxoo %}
g,{% 函数名 arg1 arg2 %}
缺点:不能作为if 条件
优点:参数任意
filter
a,app下创建templatetags目录
b,任意xxoo.pu文件
c,创建template对象 register
d,@register.filter
def func(a1,a2,..):
return "baobaohui"
e,settings 中注册 APP
f,顶部{% load xxoo %}
g,{% 函数名 arg1 arg2 %}
g,{{参数1|函数名:"参数二,参数三.."}}# 通过字符串来传多个参数
g,{{参数1|函数名:数字}}
缺点:参数任意,不能加空格
优点:能作为if 条件
实例应用:
views:
def tpl4(request):
name = "BAOBAOHUIbaobaohui"
return render(request, 'tpl4.html',{'name':name})
xxoo.py:
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag()
def baobaohui(a1,a2):
return a1+a2
@register.filter
def jiajingze(a1,a2):
print(a2,type(a2))
return a1+str(a2)
tpl4.html:
{% load xxoo %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{{ name }}
{{ name|lower }}
{{ name|truncatechars:"3" }}
{% baobaohui 2 5 %}
{{ "maliya"|jiajingze:30 }}
</body>
</html>
cookie
-views
def cookie(request)
def cookie(request):
request.COOKIES
request.COOKIES['username']
request.COOKIES.get('username')
response = render(request,'index2.html')
response = redirect('/index/')
response.set_cookie('key','value')
#设置 cookie,关闭浏览器失效
return response
def index2(request)
def index2(request):
#获取当前已经登陆的用户
v = request.COOKIES.get('username111')
print(v)
if not v:
return redirect('/login/')
return render(request,'index2.html',{'current_user':v})
def login(request)
def login(request):
if request.method == 'GET':
return render(request,'login.html')
if request.method == 'POST':
u = request.POST.get('username')
p = request.POST.get('pwd')
dic = user_info.get(u)
if not dic:
return render(request,'login.html')
if dic['pwd'] == p:
res = redirect('/index2/')
#设置 cookie N秒后失效
# res.set_cookie('username',u,max_age=10)
# 设置 cookie 截止时间失效
# import datetime
# current_date = datetime.datetime.utcnow()
# cuttent_date = current_date*datetime.timedelta(seconds=5)
# res.set_cookie('username',u,expires=current_date)
#
res.set_cookie('user_type',"ordinary",httponly=True)
res.set_cookie('username111',u)
return res
else:
return render(request,'login.html')
-templates
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login/" method="post">
<input type="text" name="username" placeholder="用户名">
<input type="text" name="pwd" placeholder="密码">
<input type="submit">
</form>
</body>
</html>
index2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎登陆:{{ current_user }}</h1>
</body>
</html>
session
静待下回分析
分页(自定义的分页)
1,XSS:
{{page_str|safe}}
mark_safe(page_str)
2,应用实例
views
from utils import pagination
LIST = []
for i in range(500):
LIST.append(i)
def user_list(request):
current_page = request.GET.get('p',1)
current_page = int(current_page)
page_obj = pagination.Page(current_page,len(LIST))
data = LIST[page_obj.start:page_obj.end]
page_str = page_obj.page_str("/user_list/")
return render(request,'user_list2.html',{'li':data,'page_str':page_str})
util
-pagination.py
#分页,具体表现形式: 上一页 1 2 3 4 5 6 7 下一页 |输入框 | GO
#根据已有页数适当进行变换
from django.utils.safestring import mark_safe
class Page:
def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
self.current_page = current_page
self.data_count = data_count
self.per_page_count = per_page_count
self.pager_num = pager_num
@property
def start(self):
return (self.current_page - 1) * self.per_page_count
@property
def end(self):
return self.current_page * self.per_page_count
@property
def total_count(self):
v, y = divmod(self.data_count, self.per_page_count)
if y:
v += 1
return v
def page_str(self, base_url):
page_list = []
if self.total_count < self.pager_num:
start_index = 1
end_index = self.total_count + 1
else:
if self.current_page <= (self.pager_num + 1) / 2:
start_index = 1
end_index = self.pager_num + 1
else:
start_index = self.current_page - (self.pager_num - 1) / 2
end_index = self.current_page + (self.pager_num + 1) / 2
if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
end_index = self.total_count + 1
start_index = self.total_count - self.pager_num + 1
if self.current_page == 1:
prev = '<a class="page" href="javascript:void(0);">上一页</a>'
else:
prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url, self.current_page - 1,)
page_list.append(prev)
for i in range(int(start_index), int(end_index)):
if i == self.current_page:
temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
else:
temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
page_list.append(temp)
if self.current_page == self.total_count:
nex = '<a class="page" href="javascript:void(0);">下一页</a>'
else:
nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url, self.current_page + 1,)
page_list.append(nex)
jump = """
<input type='text' /><a οnclick='jumpTo(this, "%s?p=");'>GO</a>
<script>
function jumpTo(ths,base){
var val = ths.previousSibling.value;
location.href = base + val;
}
</script>
""" % (base_url,)
page_list.append(jump)
page_str = mark_safe("".join(page_list))
return page_str
views
from utils import pagination
LIST = []
for i in range(500):
LIST.append(i)
def user_list(request):
current_page = request.GET.get('p',1)
current_page = int(current_page)
page_obj = pagination.Page(current_page,len(LIST))
data = LIST[page_obj.start:page_obj.end]
page_str = page_obj.page_str("/user_list/")
return render(request,'user_list2.html',{'li':data,'page_str':page_str})
li.html
<li>{{ item }}</li>
user_list2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.pagination .page{
display: inline-block;
padding: 5px;
background-color: cyan;
margin: 5px;
}
.pagination .page.active{
background-color: brown;
color: white;
}
</style>
</head>
<body>
<ul>
{% for item in li %}
{% include 'li.html' %}
{% endfor %}
</ul>
<div>
<select id="ps" onchange="changePageSize(this)">
<option value="10">10</option>
<option value="30">30</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
<div class="pagination">
{{ page_str }}
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
$(function(){
var v = $.cookie('per_page_count', {'path': "/user_list/`"});
$('#ps').val(v);
});
function changePageSize(ths){
var v = $(ths).val();
console.log(v);
$.cookie('per_page_count',v, {'path': "/user_list/"});
location.reload();
}
</script>
</body>
</html>
Form验证
缓存
中间件
信号
CSRF
Admin/ModelForm
具体详情静待下回解析