django之分页、cookie装饰器
一、分页代码如下
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装饰器 , 中间件
一: 装饰器 二: 中间件
随机推荐
- 真TM操蛋——观《鬼子来了》有感
杀日本人有罪?日本人杀中国人为何无罪?战俘?双手沾满鲜血,仇人,为何杀仇人还要被自己人判刑,被仇人斩首? 看了最后结局,我心里只有这两句话,同学说结局不好,我觉得结局恰恰很好,姜文是个很好的导演,他布 ...
- nuget github host
191.236.146.247 www.nuget.org191.236.146.247 nuget.org 192.30.253.112 github.com192.30.253.113 githu ...
- Q的深层嵌套
1.如果将异步方法用同步的方式执行,try catch能捕获到错误,同时不会阻塞到主进程,因此console.log(3333)能执行. var fs = require('fs'); try { v ...
- SpringMVC常用配置-配置DispatcherServlet映射请求路径的方式
- 可爱的Python_课后习题_CDay−3 通过函式进行功能化
1. 读取某一简单索引文件cdays−3-test.txt,其每行格式为:文档序号关键词,现须根据这些信息将它转化为倒排索引,即统计关键词在哪些文档中,格式如下:包含该关键词的文档数关键词 => ...
- [CC]区域生长算法——点云分割
基于CC写的插件,利用PCL中算法实现: void qLxPluginPCL::doRegionGrowing() { assert(m_app); if (!m_app) return; const ...
- C#写入日志信息到文件中
为了在服务器上运行程序及时的跟踪出错的地方,可以在必要的地方加入写日志的程序. string folder = string.Format(@"D:\\{0}\\{1}", Dat ...
- Python之路----------ConfigParser模块
Python的ConfigParser 废话不说,拿去用 #coding=utf-8 import configparser ''' 基於Python3.0版本寫的配置文件的創建.增加.刪除.修改等方 ...
- ios 三种对话框拉伸方法
- Excel 同时打开2个或多个独立窗口
首先win7版本点击[开始]菜单,在输入框里面输入"regedit.exe"打开注册表 然后定位找到该路径HKEY_CLASSES_ROOT \ Excel.Sheet.1 ...