django之ajax結合sweetalert使用,分頁器和bulk_create批量插入 07

sweetalert插件

有這麼一個需求:
​ 當用戶進行一個刪除數據的操做時,彈出一個二次確認的動態框樣式?
其實,這裏就能夠使用sweetalert插件實現。html

首先先下載該插件:Bootstrap-sweetalert項目前端

上圖下載完畢,解壓後找到dist文件夾,拷貝到當前項目的static文件夾下,導入此文件的兩個文件,和bootstrap框架中的css、js文件導入方式相同。python

要引入的彈出框模板在這裏:A beautiful "replacement" for JavaScript's alertjquery

示例:git

本示例選擇的彈出框和模板以下:github

swal({
  title: "Are you sure?",
  text: "You will not be able to recover this imaginary file!",
  type: "warning",
  showCancelButton: true,
  confirmButtonClass: "btn-danger",
  confirmButtonText: "Yes, delete it!",
  cancelButtonText: "No, cancel plx!",
  closeOnConfirm: false,
  closeOnCancel: false
},
function(isConfirm) {
  if (isConfirm) {
    swal("Deleted!", "Your imaginary file has been deleted.", "success");
  } else {
    swal("Cancelled", "Your imaginary file is safe :)", "error");
  }
});
# models.py

from django.db import models
# Create your models here.
class User(models.Model):
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender_choices = (
        (1,'male'),
        (2,'female'),
        (3,'others')
    )
    gender= models.IntegerField(choices=gender_choices)
# urls.py
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^home/', views.home,name='xxx'),
]

# views.py
from django.shortcuts import render

# Create your views here.
from app01 import models
from django.http import JsonResponse
def home(request):
    import time
    if request.is_ajax():
        back_dic={'code':1000,'msg':''}
        delete_id = request.POST.get('delete_id')
        time.sleep(3)
        models.User.objects.filter(pk=delete_id).delete()
        back_dic['msg']= '數據已經被刪掉了!'
        return JsonResponse(back_dic)

    queryset_obj = models.User.objects.all()
    return render(request,'home.html',locals())
<!--home.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
    <script src="{% static 'bootstrap-3.3.7/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'dist/sweetalert.js' %}"></script>
    <style>
        div.sweet-alert h2{
            padding: 10px;
        }
    </style>
</head>
<body>
<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-striped table-bordered table-hover">
                <thead>
                <tr>
                    <th>序號</th>
                    <th>姓名</th>
                    <th>年齡</th>
                    <th>性別</th>
                    <th class="text-center">操做</th>
                </tr>
                </thead>
                <tbody>
                {% for userObj in queryset_obj %}
                    <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ userObj.usernmae }}</td>
                        <td>{{ userObj.age }}</td>
                        <td>{{ userObj.get_gender_display }}</td>
                        <td class="text-center">
                            {#href爲空時,表明從新刷新頁面,因此瀏覽器頁面點擊刪除按鈕彈出框轉瞬即逝#}
                            <a href="" class="btn btn-primary btn-sm ">編輯</a>
                            {#在for循環內部不能使用id,由於id要惟一不重複,只能用class屬性,因此給class加了一個cancel#}
                            <a href="#" class="btn btn-danger btn-sm cancel" userId={{ userObj.pk }}>刪除</a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    $('.cancel').click(function () {
        {#獲取的是被點擊的a標籤對象#}
        var $btn=$(this);
        {#swal能夠填三個參數,最後一個是控制彈出框小圖標顏色的提示信息,有info和warning兩種#}
        swal({
                title: "肯定?",
                text: "刪除將不能恢復改文件了!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: "btn-danger",
                confirmButtonText: "刪除!",
                cancelButtonText: "不,取消!",
                closeOnConfirm: false,
                closeOnCancel: false,
                {#獲取加速的動態#}
                showLoaderOnConfirm:true
            },
            function (isConfirm) {
                if (isConfirm) {
                    //朝後端發送ajax請求
                    $.ajax({
                        url:'',
                        type:'post',
                        data:{'delete_id':$btn.attr('userId')},
                        success:function (data) {
                            if (data.code==1000) {
                                 swal("刪除成功!",data.msg,"success");
                                 // 經過DOM操做 來直接操做標籤,刪除標籤tr,就是當前用戶要刪除的這條數據記錄
                                 $btn.parent().parent().remove()
                            }
                        }
                    });
                } else {
                    swal("取消", "文件安全啦! :)", "錯誤");
                }
            });
    })
</script>
</body>
</html>

bulk_create 批量插入數據

當要實現批量插入數據的時候,就能夠bulk_create,能大幅度縮短插入的時間;ajax

def index(request):
    # 普通插入方式:
    # for i in range(1000):
    #         models.Book.objects.create(title='第%s本書'%i)
    # 使用bulk_create批量插入
    book_list = []
    for i in range(2000):
        book_list.append(models.Book(title='第%s本書'%i))
    models.Book.objects.bulk_create(book_list)  # 這裏直接放的是列表
    book_queryset=models.Book.objects.all()
    return render(request,'index.html',locals())
<!--index.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
 {% for book_obj in book_queryset %}
     <p>{{ book_obj.title }}</p>
 {% endfor %}
</body>
</html>

分頁器

簡易版本的分頁器的推導

def index(request):

    # 獲取用戶想要查看的頁碼
    current_page = int(request.GET.get('page', 1))
    
    book_queryset = models.Book.objects.all() # 獲取全部書籍對象
    book_num = book_queryset.count() # 統計全部書籍條數目
    book_page,more = divmod(book_num,10) # 統計書籍的分頁
    per_page_num = 10 # 定義每頁展現10條
    start_page = (current_page - 1) * per_page_num  # 每頁其實條數
    end_page = current_page * per_page_num  # 每頁終止的條數
    if more:
        book_page += 1

    html = ''
    xxx = current_page  # 對用戶的當前選頁賦值一個變量
    if current_page < 6:  
        xxx = 6  # 當用戶選擇小於6的數字,數字不會變成負數
    for i in range(xxx-5,xxx+6):  # 共展現給用戶的指定的10頁
        if current_page==i:
            # 將10頁內容的標籤以字符串的形式進行拼接,若是是當前頁,顯示激活態
            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)  # 不是當前頁的正常顯示

    book_queryset=book_queryset[start_page:end_page]
    return render(request,'index.html',locals())
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
    <script src="{% static 'bootstrap-3.3.7/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'dist/sweetalert.js' %}"></script>

</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            {% for book_obj in book_queryset %}
                <p>{{ book_obj.title }}</p>
            {% endfor %}
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li>
                        <a href="#" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                        {{ html|safe }}
                    <li>
                        <a href="#" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
</div>
</body>
</html>

自定義分頁器的使用(組件)

類封裝的組件,包括bootstrap中分頁的框架也都封裝進去了。數據庫

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)

調用以上接口:django

# views.py

def index(request):
    book_queryset = models.Book.objects.all()
    # 自定義分頁器的使用
    current_page = request.GET.get('page', 1)
    all_count = book_queryset.count()                                                        
    page_obj=Pagination(current_page,all_count,per_page_num=10,pager_count=5)
    page_queryset = book_queryset[page_obj.start:page_obj.end]
    return render(request,'index.html',locals())
// index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
    <script src="{% static 'bootstrap-3.3.7/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'dist/sweetalert.js' %}"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            {% for book_obj in page_queryset %}
                <p>{{ book_obj.title }}</p>
            {% endfor %}
            {{ page_obj.page_html|safe }}
        </div>
    </div>
</div>
</body>
</html>

django 08====>表多對多創建方式、form組件及鉤子函數

相關文章
相關標籤/搜索