How can I paginate my posts list in my homepage blog?

#view.py---------------------------------------------------------------------------------------------------------------------
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category, Comment
from .forms import PostForm, EditForm, CommentForm
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect

#Import Pagination Stuff
from django.core.paginator import Paginator

class HomeView(ListView):
	# paginate_by = 5
	model = Post
	template_name = 'home.html'
	cats = Category.objects.all()
	#ordering = ['-post_date']
	ordering = ['-id']

	def get_context_data(self, *args, **kwargs):
		cat_menu = Category.objects.all()
		context = super(HomeView, self).get_context_data(*args, **kwargs)
		context["cat_menu"] = cat_menu
		return context

home.html-----------------------------------------------------------------------------------------------------------------------

{% extends ‘base.html’ %}

{% block content %}

Posts

    {% for post in object_list %}
  • {{ post.title }}
    	- <a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a>
    	- {{ post.author.first_name }} {{ post.author.last_name }} -  
    	{{ post.post_date }} <small>
    
    	{% if user.is_authenticated %}	
    		{% if user.id == post.author.id %}
    			- <a href="{% url 'update_post' post.pk %}">(Edit)</a> 
    
    			<a href="{% url 'delete_post' post.pk %}">(Delete)</a>
    		{% endif %}
    	{% endif %}
    
    </small> <br/>
    {{ post.snippet }}</li>
    

    {% endfor %}

{% endblock %}

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

category_queryset = Category.objects.all()
category_paginator = Paginator(category_queryset, 10)

page = 1
try:
    categories = category_paginator.page(page)
except PageNotAnInteger:
    categories = category_paginator.page(1)
 except EmptyPage:
    categories = category_paginator.page(category_paginator.num_pages)

context['categories'] = categories

See the docs at Django Pagination for details on using the Paginator, especially the section on Paginating a ListView.

1 Like

Thank you, sir. But what I have tried so far wasn’t successful. could you give me some points on how can I make it work?

Please post the view you are using and the associated template that matches the pattern as shown in the doc, and we can help identify where the issues may be. Remember to enclose both the template and the view between lines of three backtick - ` characters.

1 Like

this is the link to the complete project from github