Bulk insert data, custom pager

Catalog

Using ajax with sweetalert

Click to download Bootstrap-sweetalert

One pass CV method:

<!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-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.min.js' %}"></script>

</head>
<body>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h2 class="text-center">Data display</h2>
            <br>
            <table class="table-bordered table table-striped table-hover">
                <thead>
                <tr>
                    <th>Serial number</th>
                    <th>User name</th>
                    <th>Age</th>
                    <th>Gender</th>
                    <th class="text-center">operation</th>
                </tr>
                </thead>
                <tbody>
                {% for user in user_queryset %}
                    <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ user.username }}</td>
                        <td>{{ user.age }}</td>
                        <td>{{ user.get_gender_display }}</td>
                        <td class="text-center">
                            <a href="#"Class =" BTN BTN primary BTN SM "> Edit</a>
                            <a href="#"Class =" BTN BTN danger BTN SM cancel "> delete</a>
                        </td>
                    </tr>
                {% endfor %}

                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    $('.cancel').click(function () {
        swal({
                title: "Are you sure to delete?",
                text: "If you delete it, you can run!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: "btn-danger",
                confirmButtonText: "Yes, I'll delete it!",
                cancelButtonText: "No delete.",
                closeOnConfirm: false,
                closeOnCancel: false
            },
            function (isConfirm) {
                if (isConfirm) {
                    swal("Get ready to run!", "Can't run...", "success");
                } else {
                    swal("Cancel delete", "Data is still in", "error");
                }
            });
    })
</script>

</body>
</html>

Here's a problem. I found that the Chinese characters are blocked...

Through the inspection of Google browser, you can view the html element modification and add the style:

<style>
    div.sweet-alert h2 {
    padding: 10px;
    }
</style

Final example:

<!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-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.min.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">Data display</h2>
            <br>
            <table class="table-bordered table table-striped table-hover">
                <thead>
                <tr>
                    <th>Serial number</th>
                    <th>User name</th>
                    <th>Age</th>
                    <th>Gender</th>
                    <th class="text-center">operation</th>
                </tr>
                </thead>
                <tbody>
                {% for user in user_queryset %}
                    <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ user.username }}</td>
                        <td>{{ user.age }}</td>
                        <td>{{ user.get_gender_display }}</td>
                        <td class="text-center">
                            <a href="#"Class =" BTN BTN primary BTN SM "> Edit</a>
                            <a href="#"Class =" BTN BTN danger BTN SM cancel "userid = {{user. PK}} > delete</a>
                        </td>
                    </tr>
                {% endfor %}

                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    $('.cancel').click(function () {
        var $btn = $(this);
        swal({
                title: "Are you sure to delete?",
                text: "If you delete it, you can run!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: "btn-danger",
                confirmButtonText: "Yes, I'll delete it!",
                cancelButtonText: "No delete.",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            },
            function (isConfirm) {
                if (isConfirm) {

                    // Sending ajax requests to the back end
                    $.ajax({
                        url: '',
                        type: 'post',
                        data: {'delete_id': $btn.attr('userId')},
                        success: function (data) {
                            if(data.code==1000){
                                swal("Get ready to run!", data.msg, "success");

                                // Direct manipulation of tags through DOM manipulation
                                $btn.parent().parent().remove()

                            }else {
                                swal("Yes bug", "An unknown error has occurred", "warning")
                            }
                        }
                    });

                } else {
                    swal("Cancel delete", "Data is still in", "error");
                }
            });
    })
</script>

</body>
</html>

Backend views.py

def home(request):

    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'] = 'The data has been deleted by me'
        return JsonResponse(back_dic)

    user_queryset = models.User.objects.all()
    return render(request, 'home.html', locals())

Bulk [create bulk insert data

Insert multiple pieces of data into the database in django according to the original stupidest method:

def index(request):
    for i in range(1000):
        models.Book.objects.create(title=f'The first{i}This book')

This kind of insertion is time-consuming and has great pressure on the database

Use bulk create method to insert data in bulk:

def index(request):
 

    book_list = []
    for i in range(10000):
        book_list.append(models.Book(title=f'The first{i}This book'))
    models.Book.objects.bulk_create(book_list)

    book_queryset = models.Book.objects.all()
    return render(request, 'index.html', locals())

Custom pager

Pager components

class Pagination(object):
    def __init__(self,current_page,all_count,per_page_num=2,pager_count=11):
        """
        //Encapsulate paging related data
        :param current_page: Current page
        :param all_count:    Total number of data in the database
        :param per_page_num: Number of data displayed per page
        :param pager_count:  Maximum number of pages displayed
        
        //Usage:
        queryset = model.objects.all()
        page_obj = Pagination(current_page,all_count)
        page_data = queryset[page_obj.start:page_obj.end]
        //Get data with page ﹣ data instead of the original queryset
        //To get the front-end page style, use 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


        # Total page number
        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):
        # If the total page number is less than 11:
        if self.all_pager <= self.pager_count:
            pager_start = 1
            pager_end = self.all_pager + 1
        # Total page > 11
        else:
            # If the current page is < = at most 11 / 2 pages are displayed on the page
            if self.current_page <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1

            # Current page is greater than 5
            else:
                # Page to the end
                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 = []
        # Add previous nav and ul Tags
        page_html_list.append('''
                    <nav aria-label='Page navigation>'
                    <ul class='pagination'>
                ''')
        first_page = '<li><a href="?page=%s">home page</a></li>' % (1)
        page_html_list.append(first_page)

        if self.current_page <= 1:
            prev_page = '<li class="disabled"><a href="#"> previous page
        else:
            prev_page = '<li><a href="?page=%s">Previous page</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="#"> next page
        else:
            next_page = '<li><a href="?page=%s">next page</a></li>' % (self.current_page + 1,)
        page_html_list.append(next_page)

        last_page = '<li><a href="?page=%s">Tail page</a></li>' % (self.all_pager,)
        page_html_list.append(last_page)
        # Tag tail
        page_html_list.append('''
                                           </nav>
                                           </ul>
                                       ''')
        return ''.join(page_html_list)

usage method:

Create the utils folder under app application, mypage.py under utils, and copy the above pager code

In views.py:

from app01.utils.mypage import Pagination

def index(request):
    book_queryset = models.Book.objects.all()   # Data you want to display in pages

    current_page = request.GET.get('page', 1)    # Get current page
    all_count = book_queryset.count()           # Total number of Statistics
    page_obj = Pagination(current_page=current_page, all_count=all_count, per_page_num=10, pager_count=5)   # Generate a pager object
    page_queryset = book_queryset[page_obj.start:page_obj.end]

    return render(request, 'index.html', locals())

Front end:

{% for book in book_queryset %}
    <p>{{ book }}</p>
{% endfor %}

{{ page_obj.page_html|safe }}  

Tags: Python JQuery Database Google Django

Posted on Mon, 02 Dec 2019 13:41:45 -0800 by wizardry