Django Python:无限滚动进给

eqoofvh9  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(73)

我在一个社交媒体网站上工作。我的饲料有图像和视频上传的用户,但像第6内容后,一个酒吧的按钮,以下一个网站出现(分页)。我想创建一个Infite滚动,所以如果用户达到了第一页的饲料结束时,它会自动加载下一个饲料页下的其他。
That's what appears
如果有人能帮我我会很高兴的。
我将上传我的Feed.html和Views.py
feed.html

{% extends "blog/base.html" %}

{% block title %}Feeds{% endblock %}

{% block content %}

<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />

<div class="col-8">
  
    {% if posts|length == 0 %}
      <span class="no-feed-text">
      <p>You need to follow someone to see their Posts<br>Meanwhile you can give look at your <a class="trending-page" href="{% url 'blog-trends' %}">Search</a> page</p>
      </span>
      <br><br>
    {% endif %}

    {% for post in posts %}

    
    <article class="content-section" style="overflow: auto;">
      
    
    
    

      <div class="mediacontent">
   {% if post.extension == '.mp4'%}
   <video loop controls disablePictureInPicture controlsList="nodownload noplaybackrate" class="video-context" width="500px" height="500px">
            <source src="{{ post.file.url }}" type="video/mp4">
         </video>
   {% elif post.extension == '.jpg' or post.extension == '.jpeg' %}
  <a href="{% url 'post-detail' post.id %}">
      <img class="image-context" src="{{ post.file.url }}">
    </a>
   {% endif %}
  </div>
  

  <a class="initials-modus" href="{% url 'post-detail' post.id %}">
  <div class="initials">
   <div class="media">
    <div class="img-cont3">
      <img class="rounded-circle article-img feed-pic" src="{{post.author.profile.image.url}}" alt="image">
      
    </div>
    <div class="media-body">
      
      
        <span class="mr-2 full-name-link">{{ post.author.first_name }} {{ post.author.last_name }}</span>
   
    </div>
  </div>

</div>
</a>





<div class="flex-container">

  <div class="flex-child one">
    <a class="article-title" href="{% url 'post-detail' post.id %}"><h3>{{ post.title }}</h3></a>
  </div>
  
  <div class="flex-child two">
    <a class="interactions" href="{% url 'post-detail' post.id %}"><p>2.873.938 <span>Like{{ total_likes|pluralize }}</span></p></a>
  </div>
  
</div>
        


    </article>

  
    {% endfor %}

    

    {% if posts.has_other_pages %}

      {% if posts.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={{posts.previous_page_number}}">Previous</a>
      {% endif %}

      {% for num in posts.paginator.page_range %}
        {% if posts.number == num %}
          <a class="btn btn-info mb-4" href="?page={{num}}">{{num}}</a>
        {% elif num > posts.number|add:'-3' and num < posts.number|add:'3' %}
        <a class="btn btn-outline-info mb-4" href="?page={{num}}">{{num}}</a>
        {% endif %}
      {% endfor %}

      {% if posts.has_next %}
        <a class="btn btn-outline-info mb-4" href="?page={{posts.next_page_number}}">Load more Shots</a>
        <a class="btn btn-outline-info mb-4" href="?page={{posts.paginator.num_pages}}">Last</a>
      {% endif %}

    {% endif %}
</div>   

<div class="col-4 fixed-box">

  <form class="container-box">

      <a href="{% url 'profile-detail-view' user.id %}">
      <img class="round" src="{{profile.image.url}}" alt="image">
      </a>
      <h3>{{user.first_name}} {{user.last_name}}</h3>
      <h2>@{{user.username}}</h2>
      <p>{{user.profile.bio}}</p>

        <a class="ana">
          Analytics
        </a>

  </form>







  <div class="content-section footer-div" style="background: none; border: none;">
  
    <div class="float-container">

      <div class="float-child">
        <div class="green"><a class="foot-link" href="{% url 'blog-helpcenter' %}">Help-Center</a> <br> <a class="foot-link" href="{% url 'blog-privacypolicy' %}">Privacy Policy</a> <br><a class="foot-link" href="{% url 'blog-termsofuse' %}">Terms of Service</a> <br><a class="foot-link" href="{% url 'blog-cookies' %}">Cookie Guidelines</a> <br><a class="foot-link" href="#">Report a Bug</a><br><a class="foot-link" href="#">Contact</a> <br></div>
      </div>
      
      <div class="float-child">
        <div class="blue"><a class="foot-link" href="#">News</a> <br><a class="foot-link" href="#">About</a> <br><a class="foot-link" href="#">Imprint</a> <br><a class="foot-link" href="{% url 'blog-settings' %}">Settings</a>  <br><a class="foot-link" href="{% url 'blog-press' %}">Press</a><br></div>
      </div>
      
    </div>

    <div></div>
    
    <br><br> <br><br><br><br>
    <p class="footer-brand">Social Media </p>
  
  </div>

 

</div>

<!-- mobile -->

<div class="col-12">

  
  {% if posts|length == 0 %}
      <span class="no-feed-text">
      <p>You need to follow someone to see their Posts<br>Meanwhile you can give look at your <a class="trending-page" href="{% url 'blog-trends' %}">Search</a> page</p>
      </span>
      <br><br>
    {% endif %}

    {% for post in posts %}

    
    <article class="content-section" style="overflow: auto;">
      
    
    
    

      <div class="mediacontent">
   {% if post.extension == '.mp4'%}
   <video loop controls disablePictureInPicture controlslist="nodownload noplaybackrate" class="video-context" width="500px" height="500px">
            <source src="{{ post.file.url }}" type="video/mp4">
         </video>
   {% elif post.extension == '.jpg' or post.extension == '.jpeg' %}
  <a href="{% url 'post-detail' post.id %}">
      <img class="image-context" src="{{ post.file.url }}">
    </a>
   {% endif %}
  </div>
  

  <a class="initials-modus" href="{% url 'profile-detail-view' post.author.pk %}">
  <div class="initials">
   <div class="media">
    <div class="img-cont3">
      <img class="rounded-circle article-img feed-pic" src="{{post.author.profile.image.url}}" alt="image">
      
    </div>
    <div class="media-body">
      
      
        <span class="mr-2 full-name-link">{{ post.author.first_name }} {{ post.author.last_name }}</span>
   
    </div>
  </div>

</div>
</a>





<script>
  var videos = document.querySelectorAll('video');
for(var i=0; i<videos.length; i++)
   videos[i].addEventListener('play', function(){pauseAll(this)}, true);

function pauseAll(elem){
    for(var i=0; i<videos.length; i++){
        //Is this the one we want to play?
        if(videos[i] == elem) continue;
        //Have we already played it && is it already paused?
        if(videos[i].played.length > 0 && !videos[i].paused){
        // Then pause it now
          videos[i].pause();
        }
    }
  }
</script>

<script src="/static/js/jquery-2.2.4.min.js"></script>
    <script src="/static/js/jquery.waypoints.min.js"></script>
    <script src="/static/js/infinite.min.js"></script>
    <script>
    var infinite = new Waypoint.Infinite({
        element: $('.infinite-container')[0],
        handler: function(direction) {

    },
    offset: 'bottom-in-view',

    onBeforePageLoad: function () {
    $('.spinner-border').show();
    },
    onAfterPageLoad: function () {
    $('.spinner-border').hide();
    }

    });

    </script>


<div class="flex-container">

  <div class="flex-child one">
    <a class="article-title" href="{% url 'post-detail' post.id %}"><h3>{{ post.title }}</h3></a>
  </div>
  
  <div class="flex-child two">
    <a class="interactions" href="{% url 'post-detail' post.id %}"><p>2.873.938 <span>Like{{ total_likes|pluralize }}</span></p></a>
  </div>
  
</div>
        


    </article>

  
    {% endfor %}

    

    {% if posts.has_other_pages %}

      {% if posts.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={{posts.previous_page_number}}">Previous</a>
      {% endif %}

      {% for num in posts.paginator.page_range %}
        {% if posts.number == num %}
          <a class="btn btn-info mb-4" href="?page={{num}}">{{num}}</a>
        {% elif num > posts.number|add:'-3' and num < posts.number|add:'3' %}
        <a class="btn btn-outline-info mb-4" href="?page={{num}}">{{num}}</a>
        {% endif %}
      {% endfor %}

      {% if posts.has_next %}
        <a class="btn btn-outline-info mb-4" href="?page={{posts.next_page_number}}">Next</a>
        <a class="btn btn-outline-info mb-4" href="?page={{posts.paginator.num_pages}}">Last</a>
      {% endif %}

    {% endif %}
</div> 

<!-- mobile -->

views.py

import os, datetime
from turtle import title
from urllib import request
from blog.models import Post
from notification.models import Notification
from django.core.checks import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.urls import reverse_lazy, reverse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Comment, Post
from .forms import CommentForm
from django.http import HttpResponseRedirect, JsonResponse, HttpResponse
from users.models import Profile
from itertools import chain
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.files.storage import FileSystemStorage
from django.template.loader import render_to_string
from django.shortcuts import render, redirect 
from . import models
from .forms import PostForm
import random

""" Home page with all posts """
def first(request):
    context = {
        'posts':Post.objects.all()
    }

    return render(request, 'blog/first.html', context)







""" Posts of following user profiles """
@login_required
def posts_of_following_profiles(request):

    profile = Profile.objects.get(user = request.user)
    users = [user for user in profile.following.all()]
    posts = []
    qs = None
    for u in users:
        p = Profile.objects.get(user=u)
        p_posts = p.user.post_set.all()
        posts.append(p_posts)
    my_posts = profile.profile_posts()
    posts.append(my_posts)
    if len(posts)>0:
        qs = sorted(chain(*posts), reverse=True, key=lambda obj:obj.date_posted)

    paginator = Paginator(qs, 6)
    page = request.GET.get('page')
    try:
        posts_list = paginator.page(page)
    except PageNotAnInteger:
        posts_list = paginator.page(1)
    except EmptyPage:
        posts_list = paginator.page(paginator.num_pages)
  
    return render(request,'blog/feeds.html',{'profile':profile,'posts':posts_list})

""" Post Like """
@login_required
def LikeView(request):

    post = get_object_or_404(Post, id=request.POST.get('id'))
    liked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        liked = False
        notify = Notification.objects.filter(post=post, sender=request.user, notification_type=1)
        notify.delete()
    else:
        post.likes.add(request.user)
        liked = True
        notify = Notification(post=post, sender=request.user, user=post.author, notification_type=1)
        notify.save()

    context = {
        'post':post,
        'total_likes':post.total_likes(),
        'liked':liked,
    }

    if request.is_ajax():
        html = render_to_string('blog/like_section.html',context, request=request)
        return JsonResponse({'form':html})

""" Post save """
@login_required
def SaveView(request):

    post = get_object_or_404(Post, id=request.POST.get('id'))
    saved = False
    if post.saves.filter(id=request.user.id).exists():
        post.saves.remove(request.user)
        saved = False
    else:
        post.saves.add(request.user)
        saved = True
    
    context = {
        'post':post,
        'total_saves':post.total_saves(),
        'saved':saved,
    }

    if request.is_ajax():
        html = render_to_string('blog/save_section.html',context, request=request)
        return JsonResponse({'form':html})

""" Like post comments """
@login_required
def LikeCommentView(request): # , id1, id2              id1=post.pk id2=reply.pk
    post = get_object_or_404(Comment, id=request.POST.get('id'))
    cliked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        cliked = False
    else:
        post.likes.add(request.user)
        cliked = True

    cpost = get_object_or_404(Post, id=request.POST.get('pid'))
    total_comments2 = cpost.comments.all().order_by('-id')
    total_comments = cpost.comments.all().filter(reply=None).order_by('-id')
    tcl={}
    for cmt in total_comments2:
        total_clikes = cmt.total_clikes()
        cliked = False
        if cmt.likes.filter(id=request.user.id).exists():
            cliked = True

        tcl[cmt.id] = cliked

    context = {
        'comment_form':CommentForm(),
        'post':cpost,
        'comments':total_comments,
        'total_clikes':post.total_clikes(),
        'clikes':tcl
    }

    if request.is_ajax():
        html = render_to_string('blog/comments.html',context, request=request)
        return JsonResponse({'form':html})

""" Home page with all posts """
class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html' 
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 5

    def get_context_data(self, *args,**kwargs):
        context = super(PostListView, self).get_context_data()
        users = list(User.objects.exclude(pk=self.request.user.pk))
        if len(users) > 3:
            cnt = 3
        else:
            cnt = len(users)
        random_users = random.sample(users, cnt)
        context['random_users'] = random_users
        return context

""" All the posts of the user """
class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html' 
    context_object_name = 'posts'
    paginate_by = 5

    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')


""" Post detail view """
def PostDetailView(request,pk):

    stuff = get_object_or_404(Post, id=pk)
    total_likes = stuff.total_likes()
    total_saves = stuff.total_saves()
    total_comments = stuff.comments.all().filter(reply=None).order_by('-id')
    total_comments2 = stuff.comments.all().order_by('-id')

    context = {}

    if request.method == "POST":
        comment_qs = None
        comment_form = CommentForm(request.POST or None)
        if comment_form.is_valid():
            form = request.POST.get('body')
            reply_id = request.POST.get('comment_id')
            if reply_id:
                comment_qs = Comment.objects.get(id=reply_id)
            
            comment = Comment.objects.create(name=request.user,post=stuff,body=form, reply=comment_qs)
            comment.save()
            if reply_id:
                notify = Notification(post=stuff, sender=request.user, user=stuff.author, text_preview=form, notification_type=4)
                notify.save()
            else:
                notify = Notification(post=stuff, sender=request.user, user=stuff.author, text_preview=form, notification_type=3)
                notify.save()
            total_comments = stuff.comments.all().filter(reply=None).order_by('-id')
            total_comments2 = stuff.comments.all().order_by('-id')
    else:
        comment_form = CommentForm()
             

    tcl={}
    for cmt in total_comments2:
        total_clikes = cmt.total_clikes()
        cliked = False
        if cmt.likes.filter(id=request.user.id).exists():
            cliked = True

        tcl[cmt.id] = cliked
    context["clikes"]=tcl

    liked = False
    if stuff.likes.filter(id=request.user.id).exists():
        liked = True
    context["total_likes"]=total_likes
    context["liked"]=liked

    saved = False
    if stuff.saves.filter(id=request.user.id).exists():
        saved = True
    context["total_saves"]=total_saves
    context["saved"]=saved
    

    context['comment_form'] = comment_form

    context['post']=stuff
    context['comments']=total_comments

    if request.is_ajax():
        html = render_to_string('blog/comments.html',context, request=request)
        return JsonResponse({'form':html})

    return render(request, 'blog/post_detail.html', context)

""" Create post """
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields =['title','file']

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


""" Update post """
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields =['title','file']

    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

""" Delete post """
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


""" Search by post title or username """
def search(request):
    query = request.GET['query']
    if len(query) >= 150 or len(query) < 1:
        allposts = Post.objects.none()
    elif len(query.strip()) == 0:
        allposts = Post.objects.none()
    else:
        allpostsTitle = Post.objects.filter(title__icontains=query)
        allpostsAuthor = Post.objects.filter(author__username = query)
        allposts = allpostsAuthor.union(allpostsTitle)
    
    params = {'allposts': allposts}
    return render(request, 'blog/search_results.html', params)

""" Liked posts """
@login_required
def AllLikeView(request):
    user = request.user
    liked_posts = user.blogpost.all()
    context = {
        'liked_posts':liked_posts
    }
    return render(request, 'blog/liked_posts.html', context)

""" Saved posts """
@login_required
def AllSaveView(request):
    user = request.user
    saved_posts = user.blogsave.all()
    context = {
        'saved_posts':saved_posts
    }
    return render(request, 'blog/saved_posts.html', context)

相关问题