python - 使用 django 无限滚动

标签 python html django infinite-scroll

我对网络开发相当陌生,我正在构建一个博客风格的网站。我使用分页将帖子分成单独的页面,但现在我想像 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 可以与您希望每次滚动到页面底部时显示的对象数量互换。

View .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. 
}



}


})

关于python - 使用 django 无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57031455/

相关文章:

python - 在 Raspberry PI 上安装 "ring.cx SIP client"

python - 将 python 代码放到网上 - 与我的 app.py 脚本混淆

Python 错误 : TypeError: a bytes-like object is required, 不是 'str'

javascript - 从mysql输入的html中搜索数据

javascript - 网页中的异常数据格式

python - 如何在 Django 中使用 QuerySet 过滤最新的 m2m 对象

用于移动应用程序和 Chrome 扩展的 Django CSRF 保护

Python的时间戳出错

javascript - 响应图像图片媒体大小在 Firefox 中不起作用

javascript - Django 模板中的 List.pop() 没有 for 循环