一、分页代码如下
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 onclick='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
django分页后台代码
<!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>
user_list.html
/* li.html */
<li>{{ item }}</li>
views.py文件
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) val = request.COOKIES.get('per_page_count',10)
val = int(val)
page_obj = pagination.Page(current_page,len(LIST),val) data = LIST[page_obj.start:page_obj.end] page_str = page_obj.page_str("/user_list/") return render(request, 'user_list.html', {'li': data,'page_str': page_str})
二、cookie使用
Cookie 是由 Web 服务器保存在用户浏览器(客户端)上的小文本文件,它可以包含有关用户的信息;cookie的内容主要包括:名字,值,过期时间,路径和域。
1、获取Cookie:
1
2
3
4
5
6
|
request.COOKIES[ 'key' ]
request.get_signed_cookie(key, default = RAISE_ERROR, salt = '', max_age = None )
参数:
default: 默认值
salt: 加密盐
max_age: 后台控制过期时间
|
2、设置Cookie:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
rep = HttpResponse(...) 或 rep = render(request, ...)
rep.set_cookie(key,value,...) rep.set_signed_cookie(key,value,salt = '加密盐' ,...)
参数:
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获取(不是绝对,底层抓包可以获取到也可以被覆盖)
|
由于cookie保存在客户端的电脑上,所以,JavaScript和jquery也可以操作cookie。
1
2
|
<script src = '/static/js/jquery.cookie.js' >< / script>
$.cookie( "list_pager_num" , 30 ,{ path: '/' });
|
实例:
def auth(func):
''' 装饰登录判断是否存在cookie
'''
def inner(request, *args, **kwargs):
try:
#获取加盐cookie
v = request.get_signed_cookie('NID', salt='dwadwadwa')
if not v:
return redirect('/login/')
except Exception as e:
return redirect('/login/')
return func(request, *args, **kwargs)
return inner from django.utils.decorators import method_decorator
from django import views class Order1(views.View):
"""
方法一
CBV --> class Base view
"""
@method_decorator(auth)
def get(self,request):
redirect_to = settings.LOGIN_REDIRECT_URL
res = redirect(redirect_to)
res.set_signed_cookie('NID', 'user', salt="dwadwadwa")
return res
@method_decorator(auth)
def post(self,request):
redirect_to = settings.LOGIN_REDIRECT_URL
res = redirect(redirect_to)
res.set_signed_cookie('NID', 'user', salt="dwadwadwa")
return res
class Order2(views.View):
"""
方法二
CBV --> class Base view
"""
@method_decorator(auth)
def dispatch(self, request, *args, **kwargs):
return super(Order2,self).dispatch(request,*args,**kwargs) def get(self,request):
redirect_to = settings.LOGIN_REDIRECT_URL
res = redirect(redirect_to)
res.set_signed_cookie('NID', 'user', salt="dwadwadwa")
return res def post(self,request):
redirect_to = settings.LOGIN_REDIRECT_URL
res = redirect(redirect_to)
res.set_signed_cookie('NID', 'user', salt="dwadwadwa")
return res @method_decorator(auth,name='dispatch')
class Order3(views.View):
"""
推荐使用:方法三
CBV --> class Base view
""" def get(self,request):
redirect_to = settings.LOGIN_REDIRECT_URL
res = redirect(redirect_to)
res.set_signed_cookie('NID', 'user', salt="dwadwadwa")
return res def post(self,request):
redirect_to = settings.LOGIN_REDIRECT_URL
res = redirect(redirect_to)
res.set_signed_cookie('NID', 'user', salt="dwadwadwa")
return res def login(request):
"""
FBV --> func Base view
"""
redirect_to = settings.LOGIN_REDIRECT_URL
if request.method == "GET":
return render(request, 'login.html')
if request.method == "POST":
user = request.POST.get('username')
passwd = request.POST.get('password')
obj = models.Usertype.objects.filter(username=user,password=passwd).first()
if obj:
res = redirect(redirect_to)
"""
登录成功设置cookie
"""
res.set_signed_cookie('NID', user, salt="dwadwadwa")
return res
else:
return render(request, 'login.html', {'password_is_wrong': True})
django cookie FBV&CBV使用方法
三、模块继承
模板中也有自己的语言,该语言可以实现数据展示
- {{ item }}
- {% for item in item_list %} <a>{{ item }}</a> {% endfor %}
forloop.counter
forloop.first
forloop.last - {% if ordered_warranty %} {% else %} {% endif %}
- 母板:{% block title %}{% endblock %}
子板:{% extends "base.html" %}
{% block title %}{% endblock %}
实例:
<!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>
<div>
<a>asdf</a>
<a id="">asdf</a>
<a>asdf</a>
<a>asdf</a>
<a>asdf</a>
</div>
<iframe src="/"></iframe>
</body>
</html>
master.html
{% extends 'master.html' %} {% block title %}用户管理{% endblock %} {% 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 %}
tp1.html
django之分页、cookie装饰器的更多相关文章
-
django类视图的装饰器验证
django类视图的装饰器验证 django类视图的get和post方法是由View内部调用dispatch方法来分发,最后调用as_view来完成一个视图的流程. 函数视图可以直接使用对应的装饰器 ...
-
给django视图类添加装饰器
要将login_required装饰到view class的dispatch方法上, 因为dispatch方法为类方法,不是单个的函数,所以需要将装饰函数的装饰器 login_required转化为装 ...
-
Django学习手册 - 登录装饰器
# 装饰器定义 def auth(func): def inner(request,*args,**kwargs): v = request.COOKIES.get("user") ...
-
django ----CBV中加装饰器
CBV中加装饰器 from django import views from django.utils.decorators import method_decorator def login_aut ...
-
Django中类视图使用装饰器的方式
类视图使用装饰器 为类视图添加装饰器,可以使用两种方法. 为了理解方便,我们先来定义一个为函数视图准备的装饰器(在设计装饰器时基本都以函数视图作为考虑的被装饰对象),及一个要被装饰的类视图. def ...
-
Django views 中的装饰器
关于装饰器 示例: 有返回值的装饰器:判断用户是否登录,如果登录继续执行函数,否则跳回登录界面 def auth(func): def inner(request, *args, **kwargs): ...
-
django 内置用户-装饰器
""" 一.如何给python内置用户添加额外的字段,注意一定义在没有迁移数据之前定义,否则会报错 1.在models中先调用 from django.contrib.a ...
-
django 单点登录思路-装饰器
def the_one(func): '''自定义 验唯一证在线 装饰器''' def check_login_status(request): if request.session.get('qq' ...
-
Django day15 (一) cbv装饰器 , 中间件
一: 装饰器 二: 中间件
随机推荐
-
webParts与Web部件
web部件是ASP.NET WebForm里面的服务器控件,它涵盖的内容比较多,鉴于这种状况的话鄙人不打算深究下去了,只是局限于了解web.config配置里面的配置内容则可. 那么也得稍微说说啥是W ...
-
Log4net介绍
一.Log4net介绍 log4net是一个功能著名的开源日志记录组件.利用log4net可以方便地将日志信息记录到文件.控制台.Windows事件日志和数据库(包括MS Server,Access, ...
-
Android Studio使用教程
http://blog.csdn.net/ryantang03/article/details/8948037 http://blog.csdn.net/ryantang03/article/deta ...
-
IOS第五天(1:取消按钮的监听和设置代理textField字数限制)
***********取消按钮的监听和设置代理textField字数限制 UITextFieldDelegate #import "HMViewController.h" @int ...
-
c 指针(一)
一:什么是指针 变量i 的存储地址为P(假设为2000),*P 为指针变量 一个变量的地址称为该变量的“指针”.如果有另一个变量专门存放另一变量的地址(指针),则它称为“指针变量”. 指针是一个地 ...
-
简化工作——我的bat文件
重启adb(radb.bat): @echo off call adb kill-server call adb start-server call adb remount push 一个apk(pu ...
-
Swift和OC 混编
1.首先创建一个Swift工程 2.导入或者创建一个OC文件(.h和.m) 3.再创建一个桥连接文件 4.然后文件样子为 5.在桥接链接里面导入头文件 6.通过targets->->bui ...
-
Delphi 常用函数记录
//判断是否是数字 function IsNumeric(sDestStr: string): Boolean; //简写多余汉字 function SimplifyWord(sWord: strin ...
-
CAS进行https到http的改造方案,结合cookie源码分析
先说具体的改造方案: 服务端: 一.CAS Server端的修改 1.找到cas\WEB-INF\deployerConfigContext.xml 对以下Bean增加参数p:requireSecur ...
-
Android 上传图片到服务器二--------调用相机7.0以上权限问题
[目录] (一)上传图片到服务器一 ---------------------------------Android代码 (二)上传图片到服务器二--------------------------- ...