使用django无限滚动

infinite scrolling using django

我是网络开发的新手,我正在构建一个博客风格的网站。我使用分页将帖子分成单独的页面,但现在我想像 facebook 那样进行无限滚动。

我已经观看了无数视频并阅读了一大堆与此相关的文档,但老实说,我迷失了所有这些。

我的后端使用 django 和 python,所有源似乎都使用其他语言等,如 JS 和 ajax 等

所有这些提到的来源都是从头开始的,这让我感到困惑,因为我已经有了分页。

有没有一种方法可以调整我当前的分页以启用无限滚动,而不是用不同的语言重建整个页面?或者只是帮助我以正确的方式完成这项工作。我已经为此苦苦挣扎了几个星期,所以现在我来这里是最后的选择。

如果之前没有付出任何努力,运行 就没有意义

这是我当前的分页代码:

views.py:

from django.shortcuts import render, get_object_or_404
from .models import Post
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render


class PostListView(ListView):
    model=Post
    template_name = "Fire_Ant/home.html"
    context_object_name = "posts"
    paginate_by = 4
    ordering = ["-date_posted"]

class UserPostListView(ListView):
    model=Post
    template_name = "Fire_Ant/user_posts.html"
    context_object_name = "posts"
    rdering = ["-date_posted"]
    paginate_by = 4

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get("username"))
        return Post.objects.filter(author=user).order_by("-date_posted")

class PostDetailView(DetailView):
    model=Post

class PostCreateView(LoginRequiredMixin, CreateView):
    model=Post
    fields = ["title", "content"]   

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model=Post
    fields = ["title", "content"]   

        def form_valid(self, form):
            form.instance.author = self.request.user
        return super().form_valid(form)     

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model=Post
    success_url = "/"

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

def about(request):
    return render(request,"Fire_Ant/about.html", {"title": "about"})


def home(request):
    numbers_list = range(1, 1000)
    page = request.GET.get('page', 1)
    paginator = Paginator(numbers_list, 20)
    try:
        numbers = paginator.page(page)
    except PageNotAnInteger:
        numbers = paginator.page(1)
    except EmptyPage:
        numbers = paginator.page(paginator.num_pages)
    return render(request, 'blog/home.html', {'numbers': numbers})

home.html:

             {% if is_paginated %}
                {% if page_obj.has_previous %}
                    <a class="btn btn-outline-info mb-4" href="?page=1">First</a>
                    <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
                {% endif %}
                {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                        <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
                    {% elif num > page_obj.number|add:"-3" and num < page_obj.number|add:"3" %}
                        <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
                    {% endif %}
                {% endfor %}
                {% if page_obj.has_next %}
                    <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
                    <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages}}">Last</a>
                {% endif %}
                {% endif %}

在下面的代码中,20 可以与您希望每次滚动到页面底部时显示的对象数量互换。

views.py

def callajax(request):
    if request.method == 'POST':     
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        counter = int(data['counter'])
        obj = Post.objects.all()[counter:][:20]
        data = serializers.serialize('json', obj)
        data = {'data':data'}
    return JsonResponse(data, safe=False)

js

let counter = 0

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {

function seemore(){
var counter = counter+20;
counter = counter+20;
info = {'counter': counter, 'csrfmiddlewaretoken':"{{ csrf_token }}"}
$.ajax({
  type: "POST",
  url: '{% url "callajax" %}',
  data:info,
    datatype:'json',
   headers: { "X-CSRFToken": '{{csrf_token}}' },



success: function(data){
#here you add the html to the dom that you want shown once you get to bottom of page. 
}



}


})