Django Web Development Techniques: AJAX, Bulk Operations, and Pagination

Table of Contants- Implementing Delete Confirmation with AJAX and SweetAlert

  • Customizing Element Styles
  • Efficient Batch Data Insertion with bulk_create
  • Building a Simple Pagination System
  • Utilizing Custom Pagination Classes

Implementing Delete Confirmation with AJAX and SweetAlert

Customizing Element Styles

f12-->inspect-->Styles-->background-color

f12-->inspect-->div.sweet-alert.showSweetAlert

Error: Forbidden (CSRF token missing or inocrrect.): /

Solution: settings.py-->MIDDLEWARE-->Comment out 'django.middleware.csrf.CsrfViewMiddleware',

<div>
    <style>
        div.sweet-alert.showSweetAlert {  /* Tag selector + class selector to modify background color */
            background-color: yellow;
        }

        div.sweet-alert.showSweetAlert h2 {  /* Tag selector + class selector + descendant selector to modify padding */
            padding: 25px;
        }
    </style>
</div>

| {{ user\_obj.get\_gender\_display }} | [Edit](#) | [Delete](#) |
|---|---|---|

<script>
    $('.delete-btn').on(
        'click',
        function () {
            var $button = $(this);  // Reference to the clicked a tag
            swal({
                    ...
                    showLoaderOnConfirm: true,  // Network delay waiting animation effect
                },
                function (isConfirm) {
                    if (isConfirm) {  // Send AJAX request before showing deletion confirmation
                        $.ajax({
                            url: '',
                            type: 'post',
                            data: {'delete_id': $button.attr('data-user-id')},
                            success: function (response) {
                                if (response.code == 1000) {
                                    swal('Operation Successful!', 'Data has been deleted', 'success');
                                    $button.closest('tr').remove();  // Directly remove data row without page refresh
                                }
                                ...
                            }
                        });
                    }
                }
            );
        }
    );
</script>

def home(request):
    import time

    if request.is_ajax():
        time.sleep(2)  # Simulate 2-second delay
        response_data = {'code': 1000, 'message': ''}
        delete_id = request.POST.get('delete_id')
        models.User.objects.filter(pk=delete_id).delete()
        response_data['message'] = 'Data has been deleted'

        # Typically, backend returns AJAX request processing results as a dictionary
        # JsonResponse automatically converts backend dictionary to frontend object type data
        return JsonResponse(response_data)

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

Efficient Batch Data Insertion with bulk_create

def batch_insert(request):
    book_collection = []
    for i in range(1000):
        book_instance = models.Book(title=f'Book Number {i}')  # Generate book objects and add to list
        book_collection.append(book_instance)
    models.Book.objects.bulk_create(book_collection)  # Batch insert data

Building a Simple Pagination System

def display_books(request):
    total_records = models.Book.objects.count()  # Total number of records
    items_per_page = 10  # Number of items to display per page
    total_pages, remaining_items = divmod(total_records, items_per_page)  # Total pages (floor division), remaining items after pagination
    if remaining_items:
        total_pages += 1  # If there are remaining items after pagination, add 1 to page count

    current_page = int(request.GET.get('page', 1))  # Starting page, default is 1
    pagination_html = ''  # Record pagination display page numbers
    temp_page = current_page  # Temporary variable to handle pagination left boundary display
    if temp_page <= 5:
        temp_page = 5
    for i in range(temp_page - 5, temp_page + 5):
        # Highlight the selected page number
        if i + 1 == current_page:  
            pagination_html += '<li class="active"><a href="?page=%s">%s</a></li>' % (i + 1, i + 1,)
        
        # Display 10 pages centered on the selected page
        else:  
            pagination_html += '<li><a href="?page=%s">%s</a></li>' % (i + 1, i + 1,)

    start_index = (current_page - 1) * items_per_page  # Starting index of data for current page
    end_index = current_page * items_per_page  # Ending index of data for current page

    displayed_books = models.Book.objects.all()[start_index:end_index]  # Show data for the requested page
    return render(request, 'display.html', locals())


<div>
    {% for book in displayed_books %}
        <p>{{ book.title }}</p>
    {% endfor %}
    
    <!-- Pagination start -->
     {{ pagination\_html|safe }} 
</div>

Utilizing Custom Pagination Classes

Typicaly create a utils folder to store third-party components

Django's built-in pagination module is not very user-friendly

QuerySet supports slicing operations

def display_with_pagination(request):
    total_records = models.Book.objects.count()  # Total number of records

    current_page = int(request.GET.get('page', 1))  # Current page

    queryset = models.Book.objects.all()
    page_manager = CustomPagination(current_page, total_records, 10, 10)
    page_data = queryset[page_manager.start: page_manager.end]
    return render(request, 'display.html', locals())


class CustomPagination(object):
    def __init__(self, current_page, total_count, items_per_page=10, display_pages=10):
        """
        Encapsulate pagination-related data
        :param current_page: Current page
        :param total_count: Total number of records in database
        :param items_per_page: Number of records to display per page
        :param display_pages: Number of page numbers to display in pagination

        Usage:
        queryset = model.tableName.objects.all()
        page_obj = CustomPagination(current_page, total_count, items_per_page=10, display_pages=10)
        page_data = queryset[page_obj.start:page_obj.end]
        Use page_data for displaying data on each page
        Use page_obj.page_html for pagination display and page numbers
        ...
        """

Tags: Django Ajax SweetAlert bulk_create Pagination

Posted on Sun, 16 Aug 2026 16:28:17 +0000 by andyhoneycutt