article

Sunday, June 19, 2022

Python Django Load More Data using jquery Ajax

Python Django Load More Data using jquery Ajax

Register App
 
//blogsite/settings.py
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
Creating View
Bootstrap 4 
https://getbootstrap.com/docs/4.5/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.cs

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
myapp/templates/base.html
 
#myapp/templates/base.html
{% load static %}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <title>Python Django Load More Data using jquery Ajax</title>
</head>
<body>
<div class="container mt-3">
    <p><h1>Python Django Load More Data using jquery Ajax</h1></p>
    {% block content %}{% endblock content %}
</div>
<script>
const postsBox = document.getElementById('posts-box')
console.log(postsBox)
const spinnerBox = document.getElementById('spinner-box')
const loadBtn = document.getElementById('load-btn')
const loadBox = document.getElementById('loading-box')
let visible = 3 

const handleGetData = () => {
    $.ajax({
        type: 'GET',
        url: `/posts-json/${visible}/`,
        success: function(response){
            maxSize = response.max
            const data = response.data
            spinnerBox.classList.remove('not-visible')
            setTimeout(()=>{
                spinnerBox.classList.add('not-visible')
                data.map(post=>{
                    console.log(post.id)
                    postsBox.innerHTML += `<div class="card p-3 mt-3 mb-3">
                                                ${post.post_title}
                                                <br>
                                                ${post.post_content}
                                            </div>`
                })
                if(maxSize){
                    console.log('done')
                    loadBox.innerHTML = "<h4>No more posts to load</h4>"
                }
            }, 500)
        },
        error: function(error){
            console.log(error)
        }
    })
}

handleGetData()

loadBtn.addEventListener('click', ()=>{
    visible += 3
    handleGetData()
})
</script>
<style>
    .not-visible {
        display: none;
    }
</style>    
</body>
</html>
myapp/templates/main.html
#myapp/templates/main.html
{% extends "base.html" %}

{% block content %}
    <div id="posts-box"></div>
    <div id="spinner-box" class="not-visible">
        <div class="spinner-border text-primary" role="status"></div>
    </div>
    <div id="loading-box">
        <button class="btn btn-primary" id="load-btn">Load more</button>
    </div>
{% endblock content %}
Model
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\blogsite>python manage.py makemigrations
C:\django\blogsite>python manage.py migrate
myapp/models.py
#myapp/models.py
from django.db import models

# Create your models here.
class Post(models.Model):
    post_title = models.CharField(max_length=200)
    post_content = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)

    class Meta:
        ordering = ('-created',)
myapp/views.py
 
#myapp/views.py
from django.shortcuts import render
from django.views.generic import View, TemplateView
from .models import Post
from django.http import JsonResponse

class MainView(TemplateView):
    template_name = 'main.html'

class PostJsonListView(View):
    def get(self, *args, **kwargs):
        print(kwargs)
        upper = kwargs.get('num_posts')
        lower = upper - 3 
        posts = list(Post.objects.values()[lower:upper])
        posts_size = len(Post.objects.all())
        max_size = True if upper >= posts_size else False
        return JsonResponse({'data': posts, 'max': max_size}, safe=False)	
blogsite/urls.py
 
#blogsite/urls.py
from django.contrib import admin
from django.urls import path

from myapp.views import MainView, PostJsonListView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', MainView.as_view(), name='main-view'),
    path('posts-json/<int:num_posts>/', PostJsonListView.as_view(), name='posts-json-view'),
]
Run : C:\django\blogsite>python manage.py runserver

Related Post