Проблемы с автоматической пагинацией в Django, как исправить дубликаты постов?

Проблема заключается в том, что при автоматической пагинации появляются дубликаты постов. Если в цикле {% for post in post_lists %} в шаблоне home.html задан вывод 5 опубликованных постов, то при автоматической пагинации из шаблона home_list.html добавляются дубликаты этих 5 опубликованных постов, что неправильно. Автоматическая пагинация работает корректно и отображает все опубликованные посты правильно. Проблема заключается только в дублировании первых пяти опубликованных постов; остальные посты не дублируются и отображаются правильно. Как это исправить?

home.html:

{% for post in post_lists %}
<div class="post_content" id="post_content">
<!----code for displaying posts goes here---->
</div>
{% endfor %}
<div id="pagination-loader" class="pagination_pages" data-page="1"></div>
</div>
<script>
$(document).ready(function(){
    var loadedPage = 1; // Variable to store the loaded page number

    // Function to load the next batch of posts
    function loadNextPage() {
        // Perform an AJAX request to the server
        var nextPageUrl = '/load-posts/?page=' + loadedPage;
        console.log("Next page URL:", nextPageUrl);

        $.ajax({
            url: nextPageUrl,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                console.log("Response from server:", response);

                // Check for post data in the JSON response
                if (response.posts) {
                    // Add HTML with posts to the end of the container
                    $('#post_contenter').append(response.html_posts);

                    // Check if there are more posts on the next page
                    if (response.next_page_url) {
                        // Increment the value of the loadedPage variable
                        loadedPage++;
                    } else {
                        // If there is no next page, hide the loading indicator
                        $('#pagination-loader').hide();
                    }
                } else {
                    // If there is no post data, display an error message
                    console.error('Error loading posts: Post data is missing in the JSON response');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Handle the request error if it occurs
                console.error('Error loading posts:', textStatus, errorThrown);
            }
        });
    }

    // Event handler for page scrolling
    $(window).on('scroll', function() {
        // Get the current scroll position
        var scrollPosition = $(window).scrollTop();
        // Get the height of the browser window
        var windowHeight = $(window).height();
        // Get the height of the entire document
        var documentHeight = $(document).height();
        
        // If the user has scrolled to the end of the page
        if (scrollPosition + windowHeight >= documentHeight) {
            // Check if the loading indicator is visible
            if ($('#pagination-loader').is(':visible')) {
                // Load the next batch of posts
                loadNextPage();
            }
        }
    });

    // Check if the first page of posts needs to be loaded when the page is loaded
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
        loadNextPage();
    }
});
</script>

home_list.html:

{% if posts %}
    <div class="post-list">
        {% for post in posts %}
<div class="post_content" id="post_content">
<!----code for displaying posts goes here---->
</div>
</div>
       {% endfor %}
{% endif %}

views.py:

Две ключевые ноты

  1. Вам нужно упорядочить id с time_create, я предполагаю, что вы тестируете и создаете посты в цикле, иногда это может привести к появлению постов с одинаковым time_create

    .
  2. Это ограничение обычного пагинатора (Limit/Offset), используйте вместо него курсорный пагинатор

Поддерживается в DRF как rest_framework.pagination.CursorPagination, используйте его в django_paginator_class

Проблема :-

{% for post in post_lists %}
<div class="post_content" id="post_content">
<!----  PAGE 1 ALREADY LOADED HERE  ---->
</div>
{% endfor %}
<div id="pagination-loader" class="pagination_pages" data-page="1"></div>
</div>
<script>
$(document).ready(function(){
    var loadedPage = 1; // Variable to store the loaded page number

    // Function to load the next batch of posts
    function loadNextPage() {
        // Perform an AJAX request to the server
        var nextPageUrl = '/load-posts/?page=' + loadedPage;

// HERE YOU LOAD, ALREADY LOADED PAGE AGAIN 

Смотрите комментарии в коде. Первая страница уже загружена. Но вы снова загружаете первую страницу с js. Вот в чем проблема.

Ответ:

var nextPageUrl = '/load-posts/?page=' + (loadedPage + 1);
Вернуться на верх