@X-yro

Почему не работает пагинация Django с ajax?

Здравствуйте, решил я сделать пагинацию для своего поля комментариев на ajax в django, без ajax все пашет но когда я подрубаю этот скрипт по какой-то причине он не работает. То-есть при нажатии на кнопку для перехода к следующим комментам, поле с комментариями просто становится пустое, хотя при просмотре консоли в браузере, он там передает адрес для следующих комментариев.

views.py:

class ProjectDetail(DetailView):
    model = PortfolioStructure
    template_name = 'WebPortfolioApp/details.html'
    slug_url_kwarg = 'proj_slug'
    context_object_name = 'project'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context["other_blog_posts"] = Comment.objects.all().order_by('id')
        paginator = Paginator(context["other_blog_posts"], 3)
        page_two = self.request.GET.get("other-page")
        try:
            context["other_blog_posts"] = paginator.page(page_two)
        except PageNotAnInteger:
            context["other_blog_posts"] = paginator.page(1)
        except EmptyPage:
            context["other_blog_posts"] = paginator.page(paginator.num_pages)

        stuff = get_object_or_404(PortfolioStructure, slug=self.kwargs['proj_slug'])
        total_likes = stuff.total_likes()

        liked = False
        if stuff.likes.filter(id=self.request.user.id).exists():
            liked = True

        context['total_likes'] = total_likes
        context['liked'] = liked
        return context


pagination-two.html:

<div class="container mt-5">
    <nav id="pagination-two">
        <ul class="pagination justify-content-center">
            {% if other_blog_posts.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="{{ request.path }}?other-page={{ other_blog_posts.previous_page_number }}"><</a>
                </li>
            {% else %}
                <li class="page-item disabled">
                    <a class="page-link" href="#" tabindex="1" aria-disabled="true"><</a>
                </li>
            {% endif %}
            {% for i in other_blog_posts.paginator.page_range %}
                {% if other_blog_posts.number == i %}
                    <li class="page-item active">
                        <a class="page-link" href="{{ request.path }}?other-page={{ i }}">{{ i }}</a>
                    </li>
                {% else %}
                    <li class="page-item">
                        <a class="page-link" href="{{ request.path }}?other-page={{ i }}">{{ i }}</a>
                    </li>
                {% endif %}
            {% endfor %}
            {% if other_blog_posts.has_next %}
                <li class="page-item">
                    <a class="page-link" href="{{ request.path }}?other-page={{ other_blog_posts.next_page_number }}">></a>
                </li>
            {% else %}
                <li class="page-item disabled">
                    <a class="page-link" href="#" tabindex="-1" aria-disabled="true">></a>
                </li>
            {% endif %}
        </ul>
    </nav>
</div>


details.html:

<h2 class="mb-4">Comments...</h2>
            <div id="other-blog-posts">
                {% if not other_blog_posts %}
                    No Comments Yet...<div class="mb-4"><a class="link-primary" href="{% url 'add_comment' project.slug %}">Add comment</a></div>

                {% else %}
                {% if user.is_authenticated %}
                <div class="mb-3"><a class="link-primary" href="{% url 'add_comment' project.slug %}">Add comment</a></div>
                {% else  %}
                <div class="mb-3"><a class="link-primary" href="{% url 'login' %}">Login to add comment</a></div>
                {% endif %}
                    {% for comment in other_blog_posts %}
                    <strong>
                        {{ comment.name }} -
                        {{ comment.date_added }}
                        {% if user == comment.commentator %}
                                <a class="fw-normal link-primary" href="{% url 'edit_comment' comment.pk %}">[edit]</a>
                                <a class="fw-normal link-primary" href="{% url 'delete_comment' comment.pk %}">[delete]</a>
                        {% endif %}
                    </strong>
                    <br>
                    <p>{{ comment.body }}</p>
                    <br>
                    <br>
                    {% endfor %}
                {% endif %}
            </div>
            {% include 'WebPortfolioApp/pagination-two.html' %}


ajax code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js" integrity="sha512-2rNj2KJ+D8s1ceNasTIex6z4HWyOnEYLVC3FigGOmyQCZc2eBXKgOxQmo3oKLHyfcj53uz4QMsRCWNbLd32Q1g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script>
    function ajaxPaginationTwo() {
        $('#pagination-two a.page-link').each((index, el) => {
            $(el).click((e) => {
                e.preventDefault()
                let page_url = $(el).attr('href')
                console.log( page_url )

                $.ajax({
                    url: page_url,
                    type: 'GET',
                    success: (data) => {
                        $('#other-blog-posts').empty()
                        $('#other-blog-posts').append( $(data).filter('#other-blog-posts').html() )

                        $('#pagination-two').empty()
                        $('#pagination-two').append( $(data).find('#pagination-two').html() )
                    }
                })
            })
        })
    }

    $(document).ready(function() {
        ajaxPaginationTwo()
    })

    $(document).ajaxStop(function() {
        ajaxPaginationTwo()
    })
</script>
  • Вопрос задан
  • 56 просмотров
Пригласить эксперта
Ответы на вопрос 1
exibite777
@exibite777
Ведущий системный аналитик
Теоретические основы пагинации на Джанго, надеюсь не нужно вам объяснять, если нужно, то посмотрите вот тут https://qna.habr.com/q/1117578#answer_2121466
Код старенький и без моделей, но суть думаю понятна

В полотно ваше, извините, не вчитывался, но по постановке вопроса скажу: это не имеет никакого отношения к Джанго. Если делаете докрутку каких данных по кнопке или при пролистывании страницы внизу, то очень важно полученный AJAX-ответ правильно имплементировать в DOM. На своем примере: у меня AJAX обращался ко вьюхе, которая отдавала стандартный шаблонизированный Джанго рендер, но не всей страницы, а только того, что нужно, (блок с пять элементами)

Имплементация в DOM примерно так выглядела
<script type="text/javascript">
        window.need_page={{ page|add:"1" }};
        window.addEventListener('scroll', function() {
        let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
        if (windowRelativeBottom < document.documentElement.clientHeight + 100) {
            if (window.need_load_more == 1) {
                window.need_load_more = 0;
            var myDivPaginator = document.getElementById("paginatorTop");
            var myDivContent = document.getElementById("publication_content_block");
            $.ajax({
                url: "/ajaxMorePub/?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=" + window.need_page + "&size={{ size }}&order={{ order }}&direction={{ direction }}",
                success: function(response){
                  var parser = new DOMParser();
                  var ajax_html = parser.parseFromString(response, "text/html");
                  var container = ajax_html.getElementsByClassName("container")[0];
                  if (container.id != "empty") {
                          myDivContent.insertAdjacentHTML('beforeEnd', ajax_html.getElementById("pubcontent").outerHTML);
                          myDivPaginator.innerHTML = ajax_html.getElementById("paginatorTop").outerHTML;
    if (history.pushState) {
        var baseUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
        var newUrl = baseUrl + `?cat={{ cat_id_join }}{% if tag.0 != "" %}&tag={{ tagstr_param }}{% endif %}&page=` + window.need_page + `&size={{ size }}&order={{ order }}&direction={{ direction }}`;
        history.pushState(null, null, newUrl);
             }
                          window.need_page = window.need_page + 1;
                          window.need_load_more = 1;
                          }
                   else { var text_on_spinner = document.getElementById("text_on_spinner");
                          text_on_spinner.innerHTML = "Это все публикации, загляните позже или измените фильтр!!!";
                          var spinner = document.getElementById("spinner_class");
                          spinner.className="alert alert-danger";
                          return;
                          }
                     }
                  });
                };
              };
            }); </script>
Комментировать не буду, если коротко:
1. Просто берем и просто прикладываем в нужное место отрендереный кусок страницы (заменяем контейнер контентом)
2. Добавляем новый контейнер под следующий кусок
Далее по вкусу, в моем случае перерисовывался актуальный статус пагниатора
, в историю добавляется страница
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 13:31
10000 руб./за проект
19 апр. 2024, в 13:12
35000 руб./за проект
19 апр. 2024, в 13:06
6000 руб./за проект