程序目录
urls.py
"""s14_day21 URL Configuration
"""
from django.contrib import admin
from django.conf.urls import url,include
from app01 import views
urlpatterns = [
# url(r'admin/', admin.site.urls),
# url(r'index/',views.index),
# url(r'index/',views.index,{'name':"root"}),
url(r'^a/', include('app01.urls', namespace='author_1')),
# url(r'^b/', include('app01.urls', namespace='publisher-polls')),
#
url(r'tpl1', views.tpl_1),
url(r'^tpl2', views.tpl_2),
url(r'^tpl3', views.tpl_3),
url(r'tpl4', views.tpl_4),
url(r'user_lis/',views.user_lis),
url(r'login/',views.login),
url(r'index/',views.index),
url(r'order/',views.Order.as_view()),
]
app01-->urls.py
"""s14_day21 URL Configuration
"""
from django.contrib import admin
from django.conf.urls import url
from app01 import views
app_name='app01'
urlpatterns = [
url(r'^indexx/',views.indexx, name='indexxy'),
]
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
app01-->views.py
from django.shortcuts import render,HttpResponse,redirect
from django.urls import reverse
# Create your views here.
def indexx(request):
# print(name)
v= reverse('author_1:indexxy')
print(v)
# from django.core.handlers.wsgi import WSGIRequest
# print(type(request))
# environ封装了所有用户请求信息
# print(request.environ)
# for k,v in request.environ.items():
# print(k,':',v)
# request.POST
# request.GET
# request.COOKIES
# print(request.environ['HTTP_USER_AGENT'])
return HttpResponse('ok')
def tpl_2(request):
name='root'
return render(request,'tpl2.html',{'name':name})
def tpl_3(request):
status="已删除"
return render(request,'tpl3.html',{'status':status})
def tpl_1(request):
user_li=[1,2,3,4]
name = 'tpl_1'
return render(request,'tpl1.html',{'u':user_li})
def tpl_4(request):
name="TYGHijghjj112"
return render(request,'tpl4.html',{'name':name})
li=[]
for i in range(1009):
li.append(i)
from utils.pagetion import Page
def user_lis(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=Page(current_page,len(li),val)
data=li[Page_obj.start:Page_obj.end]
page_str=Page_obj.page_str("/user_lis/")
return render(request,'user_lis.html',{'li':data,'page_str':page_str})
########################## cookie ###########################
user_info_2={
'dachengzi':{'pwd':'123123'},
"kangbazi":{'pwd':'kkkkkk'},
}
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_2.get(u)
if not dic:
return render(request,'login.html')
if dic['pwd']==p:
res=redirect('/index/')
res.set_cookie('username111',u)
res.set_cookie('user_type','asdsdd',httponly=True)
# import datetime
# current_date = datetime.datetime.utcnow()
# current_date=current_date+datetime.timedelta(seconds=5)
# res.set_cookie('username111', u, expires=current_date)
return res
else:
return render(request, 'login.html')
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
@auth
def index(request):
#获取当前已经登录的用户
v=request.COOKIES.get('username111')
return render(request,'index.html',{'current_user':v})
from django import views
from django.utils.decorators import method_decorator
@method_decorator(auth,name='dispatch') #对Order类里的dispatch方法进行装饰auth
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})
def order(request):
#获取当前已经登录的用户
v=request.COOKIES.get('username111')
return render(request,'index.html',{'current_user':v})
def cookie(request):
#字典
request.COOKIES['username111']
request.COOKIES.get('username111')
response=render(request,'index.html')
response=redirect('/index/')
#设置cookie,关闭浏览器cookie就失效
response.set_cookie('key','value')
# 设置cookie,10秒后cookie就失效
response.set_cookie('username111', 'value', max_age=10)
# 设置cookie,到哪个时间节点失效
import datetime
current_date = datetime.datetime.utcnow()
current_date = current_date + datetime.timedelta(seconds=5)
response.set_cookie('username111', 'value', expires=current_date)
import datetime
current_date=datetime.datetime.utcnow()
# 获取cookie
request.COOKIES.get('....')
# 设置cookie
response.set_cookie("...")
obj=HttpResponse('s')
obj.set_signed_cookie('username','kbz',salt='aaassdf')
request.get_signed_cookie('username',salt='aaassdf')
return response
templates-->master.html
<!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:48px;
background-color: seashell;
color:green;
}
</style>
{% block css %}{% endblock %}
</head>
<body>
<div class="pg-header">管理</div>
{% block content %}{% endblock %}
<script src="/static/jquery.js"></script>
{% block js %}{% endblock %}
</body>
</html>
tempaltes-->tag.html
<div style="color: red">{{ name }}</div>
<div dd_name="尾品汇_列表_即将结束 " class="list_con">
<ul class="list_aa clearfix">
<li class="">
<a dd_name="all|21671|625|1" href="http://v.dangdang.com/pn21671_625_1.html" target="_blank" class="img"
title="迪士尼宝宝年货节">
<img data-original="http://img54.ddimg.cn/216710039996594_y.jpg"
src="http://img54.ddimg.cn/216710039996594_y.jpg" alt="迪士尼宝宝年货节" width="350" height="260"
style="display: inline;">
<span class="sale_time">
<span overtype="5" js="true" action="countdown"
type="seckill" class="time"
endvalue="1577757600" showtype="3"><span
sec="sep">还剩<span>191</span>天</span></span>
<span class="sale"></span>
</span>
<span class="red_circle" style="display: none;"></span>
<span class="little_logo">
<img data-original="http://img56.ddimg.cn/216710039996596_y.jpg"
src="http://img56.ddimg.cn/216710039996596_y.jpg"
width="115" height="40"
style="display: inline;">
</span>
<span class="price_s">
1.4<span>折起</span> </span>
</a>
</li>
</ul>
</div>
tpl1.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: green;
}
</style>
{% endblock %}
{% block js %}
<script></script>
{% endblock %}
static-->commons.css
body{
margin: 0;
}
tpl2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/commons.css">
<style>
.pg-header{
height:48px;
background-color: seashell;
color:green;
}
</style>
</head>
<body>
<div class="pg-header">管理</div>
<h1>修改密码{{ name }}</h1>
<script src="/static/jquery.js"></script>
</body>
</html>
tpl3.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/commons.css">
<style>
.pg-header{
height:48px;
background-color: seashell;
color:green;
}
</style>
</head>
<body>
<div class="pg-header">管理</div>
<h3>{{ status }}</h3>
<script src="/static/jquery.js"></script>
</body>
</html>
templatetags-->xxoo.py
from django import template
from django.utils.safestring import mark_safe
register=template.Library()
@register.simple_tag
def hou(a1,a2):
return a1+a2
@register.filter()
def jz(a1,a2):
return a1+a2 #str(数字)
templates-->tpl4.html
{% load xxoo %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>{{ name }}</div>
<div>{{ name|lower }}</div>
{{ name|truncatewords:"30" }}
{% hou 2 9 %}
{{ "maliya" | jz:"LSS" }}
<script src="/static/jquery-1.12.4.js"></script>
{% if "maliya"|jz:"LSS" %}
alert(123)
{% endif %}
</body>
</html>
views.py.bak
from django.shortcuts import render,HttpResponse,redirect
from django.urls import reverse
# Create your views here.
def index(request):
# print(name)
v= reverse('author:index')
print(v)
from django.core.handlers.wsgi import WSGIRequest
# print(type(request))
# environ封装了所有用户请求信息
# print(request.environ)
# for k,v in request.environ.items():
# print(k,':',v)
# request.POST
# request.GET
# request.COOKIES
print(request.environ['HTTP_USER_AGENT'])
return HttpResponse('ok')
def tpl_2(request):
name='root'
return render(request,'tpl2.html',{'name':name})
def tpl_3(request):
status="已删除"
return render(request,'tpl3.html',{'status':status})
def tpl_1(request):
user_li=[1,2,3,4]
name = 'tpl_1'
return render(request,'tpl1.html',{'u':user_li})
def tpl_4(request):
name="TYGHijghjj112"
return render(request,'tpl4.html',{'name':name})
li=[]
for i in range(1009):
li.append(i)
def user_lis(request):
# data=li[0:10]
# data = li[10:20]
current_page=request.GET.get('p',1)
current_page=int(current_page)
per_page_count=10
pager_num = 11
start=(current_page-1)*per_page_count
end=current_page * per_page_count
data=li[start:end]
from django.utils.safestring import mark_safe
all_count = len(li)
total_count,y=divmod(all_count,per_page_count)
if y:
total_count+=1
page_list=[]
# start_index=1
# end_index=count+1
# start_index = current_page -5
# end_index = current_page +6
if total_count<pager_num:
start_index=1
end_index=total_count+1
else:
if current_page<=(pager_num+1)/2:
start_index=1
end_index=pager_num+1
else:
start_index=current_page -(pager_num-1)/2
end_index=current_page +(pager_num+1)/2
if (current_page+(pager_num-1)/2)>total_count:
end_index=total_count +1
start_index=total_count -pager_num +1
if current_page==1:
prev="<a class='page' href='#'>上一页</a>"
else:
prev="<a class='page' href='/user_lis/?p=%s'>上一页</a>"%(current_page-1,)
page_list.append(prev)
for i in range(int(start_index),int(end_index)):
if i == current_page:
temp="<a class='page active' href='/user_lis/?p=%s'>%s</a>"%(i,i)
else:
temp = "<a class='page' href='/user_lis/?p=%s'>%s</a>"%(i,i)
page_list.append(temp)
if current_page==total_count:
nex = "<a class='page' href='javascript:void(0);'>下一页</a>"
else:
nex = "<a class='page' href='/user_lis/?p=%s'>下一页</a>" % (current_page + 1,)
page_list.append(nex)
jump="""
<input type="text" /><a onclick="jumpTo(this, '/user_lis/?p=');">GO</a>
<script>
function jumpTo(ths,base){
var val= ths.previousSibling.value;
location.href = base + val;
}
</script>
"""
page_list.append(jump)
page_str="".join(page_list)
page_str=mark_safe(page_str) #转换成安全的代码
return render(request,'user_lis.html',{'li':data,'page_str':page_str})
utils-->pagetion.py
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 = []
# start_index=1
# end_index=count+1
# start_index = current_page -5
# end_index = current_page +6
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='#'>上一页</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)
from django.utils.safestring import mark_safe
page_str = "".join(page_list)
page_str = mark_safe(page_str) # 转换成安全的代码
return page_str
user_lis.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>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="sel" 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',v,{'path':'/user_lis'});
$('#sel').val(v)
});
function changePageSize(ths) {
var v= $(ths).val();
$.cookie('per_page_count',v,{'path':"/user_lis"});
location.reload();
}
</script>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎登录:{{current_user}}</h1>
</body>
</html>