目录
Ajax结合sweetalert实现按钮动态效果
首先我们需要先到路由层做好对应的路由
from django.conf.urls import url
from django.contrib import admin
from day01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.home)
]
然后在视图函数中返回对应的HTML页面
def home(request):
user_queryset = models.User.objects.all()
return render(request,'home.html',locals())
然后在models中将库建好
class User(models.Model):
username = models.CharField(max_length=32)
age = models.IntegerField()
gender_choices = (
(1, 'male'),
(2, 'female'),
(3, 'other'),
)
gender = models.IntegerField(choices=gender_choices)
然后将数据显示在HTML文件上
首先导入相关文件
将文件存在static文件中
然后在settings.py中写下STATICFILES_DIRS = [os.path.join(BASE_DIR,‘static’)]
<!--静态文件动态配置-->
{% load static %}
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
<script src="{% static 'dist/sweetalert.js' %}"></script>
<script src="{% static 'jQuery/jQuery.js' %}"></script>
数据展示
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2 class="text-center">数据展示</h2>
<br>
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>序号</th>
<th>用户名</th>
<th>年龄</th>
<th>性别</th>
<th class="text-center">操作</th>
</tr>
</thead>
<tbody>
{% for userObj in user_queryset %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ userObj.username }}</td>
<td>{{ userObj.age }}</td>
<td>{{ userObj.get_gender_display }}</td>
<td class="text-center">
<a href="#" class="btn btn-success btn-sm">新增</a>
<a href="#" class="btn btn-danger btn-sm center user_id = {{ userObj.pk }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
添加点击事件(点击特效来自bootstrap)
<script>
$('.center').click(function () {
var $btn = $(this);
swal({
title: "你确认吗?",
text: "这个文件将无法恢复!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "给老子删了!",
cancelButtonText: "别删,手滑了",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
//当点击确定时添加ajax请求
$.ajax({
url: '',
type: 'post',
data: {'delete_id': $btn.attr('user_id')},
success: function (data) {
if (data.code == 1000) {
swal('发生了未知的错误', '{{ data.msg }}', 'success');
$btn.parent().parent().remove() // DOM操作删除按钮所在的tr
} else {
swal('有BUG', '发生了未知错误!', 'warning')
}
}
});
swal("删除成功!", "准备跑路吧!:)", "success");
} else {
swal("返回", "数据安全了! :)", "error");
}
});
})
</script>
后端处理Ajax请求
from django.http import JsonResponse # 先导入模块传字典
def home(request):
if request.is_ajax(): #判断请求是否为Ajax请求
back_dic = {'code':1000,'msg':''}
delete_id = request.POST.get('delete_id')
models.User.objects.filter(pk=delete_id).delete()
back_dic['msg']='数据已经被我删了'
return JsonResponse(back_dic)
Ajax结合sweetalert
参考代码即可 CV大法结合二次开发
bulk_create批量插入数据
传统插入数据:
def index(request):
for i in range(1000):
models.Book.objects.create(title='第%s本书'%i)
book_queryset = models.Book.objects.all()
return rander(request,'index.html',locals())
直接给数据库干爆了
使用django
orm自带的bulk_create批量插入数据
def index(request):
book_list = []
for i in range(10000):
book_list.append(models.Book(title='第%s本书'%i))
models.Book.objects.bulk_create(book_list)
book_queryset = models.Book.objects.all()
return rander(request,'index.html',locals())
低配版分页器推导
queryset
对象的切片操作
current_page = request.Get.get('page',1)
try:
current-page = int(current_page) #转成int类型
except Exception as e:
print(e)
per_page_num = 10 # 一次展示几条数据
start_page = (current_page - 1) * per_page_num #起始页
end_page = current_page * per_page_num #尾页
book_queryset = models.Book.objects.all()[start_page:end_page]
从bootcss拿到分页代码 并开发
{% for book in book_queryset %}
<P>
{{ book }}
</P>
{% endfor %}
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{{ html|safe }}
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
推导
book_queryset = models.Book.objects.all()
per_page_num = 10
all_count = book_queryset.count()
all_page_num,more = divmod(all_count,per_page_num)
if more:
all_page_num += 1
html = ''
if current_page < 6:
xxx = 6
for i in range(xxx-5,xxx+6):
if current_page ==i:
html += '<li class="active"><a href="?page=%s">%s</a></li>'%(i,i)
else:
html += '<li><a href="?page=%s">%s</a></li>'%(i,i)
自定义分页器的使用
拷自小袁添加到utils
文件中的mypage.py
class Pagination(object):
def __init__(self,current_page,all_count,per_page_num=2,pager_count=11):
"""
封装分页相关数据
:param current_page: 当前页
:param all_count: 数据库中的数据总条数
:param per_page_num: 每页显示的数据条数
:param pager_count: 最多显示的页码个数
用法:
queryset = model.objects.all()
page_obj = Pagination(current_page,all_count)
page_data = queryset[page_obj.start:page_obj.end]
获取数据用page_data而不再使用原始的queryset
获取前端分页样式用page_obj.page_html
"""
try:
current_page = int(current_page)
except Exception as e:
current_page = 1
if current_page <1:
current_page = 1
self.current_page = current_page
self.all_count = all_count
self.per_page_num = per_page_num
# 总页码
all_pager, tmp = divmod(all_count, per_page_num)
if tmp:
all_pager += 1
self.all_pager = all_pager
self.pager_count = pager_count
self.pager_count_half = int((pager_count - 1) / 2)
@property
def start(self):
return (self.current_page - 1) * self.per_page_num
@property
def end(self):
return self.current_page * self.per_page_num
def page_html(self):
# 如果总页码 < 11个:
if self.all_pager <= self.pager_count:
pager_start = 1
pager_end = self.all_pager + 1
# 总页码 > 11
else:
# 当前页如果<=页面上最多显示11/2个页码
if self.current_page <= self.pager_count_half:
pager_start = 1
pager_end = self.pager_count + 1
# 当前页大于5
else:
# 页码翻到最后
if (self.current_page + self.pager_count_half) > self.all_pager:
pager_end = self.all_pager + 1
pager_start = self.all_pager - self.pager_count + 1
else:
pager_start = self.current_page - self.pager_count_half
pager_end = self.current_page + self.pager_count_half + 1
page_html_list = []
# 添加前面的nav和ul标签
page_html_list.append('''
<nav aria-label='Page navigation>'
<ul class='pagination'>
''')
first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
page_html_list.append(first_page)
if self.current_page <= 1:
prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
else:
prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,)
page_html_list.append(prev_page)
for i in range(pager_start, pager_end):
if i == self.current_page:
temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
else:
temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
page_html_list.append(temp)
if self.current_page >= self.all_pager:
next_page = '<li class="disabled"><a href="#">下一页</a></li>'
else:
next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
page_html_list.append(next_page)
last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
page_html_list.append(last_page)
# 尾部添加标签
page_html_list.append('''
</nav>
</ul>
''')
return ''.join(page_html_list)
需要掌握的使用方法:
后端
from app01.utils.mypage import Pagination
def index(request):
current_page = request.GET.get('page',1) # 你想要的分页展示的数据
all_count = book_queryset.count() # 获取当前页面
page_obj = Pagination(current_page=current_page,all_count=all_count,per_page_num=10,pager_count=5) # 生成一个分页器对象
page_queryset = book_queryset[page_obj.start:page_obj.end]
前端
{% for book in page_queryset %}
<P>
{{ book }}
</P>
{% endfor %}
{{ page_obj.page_html|safe }} # 自动渲染所有的页面及样式