article

Monday, May 18, 2020

Django How to Add Pagination to Blog Application


Django How to Add Pagination to Blog Application

Django Build a blog application with bootstrap and Automatically Generate slugs

#views.py
from django.shortcuts import render, redirect

from django.views import generic
from myapp.models import Post

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

def index(request):
    object_list = Post.objects.filter(status=1).order_by('-created_on')
    paginator = Paginator(object_list, 3)  # 3 posts in each page
    page = request.GET.get('page')
    try:
        post_list = paginator.page(page)
    except PageNotAnInteger:
            # If page is not an integer deliver the first page
        post_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range deliver last page of results
        post_list = paginator.page(paginator.num_pages)
    return render(request,
                  'index.html',
                  {'page': page,
                   'post_list': post_list})
 
class PostDetail(generic.DetailView):
    model = Post
    template_name = 'post_detail.html'
//templates/index.html
{% extends 'base.html' %}

{% block content %}
    {% for post in post_list %}    
  <div class="post-preview">
          <a href="{% url 'post_detail' post.slug  %}">
            <h2 class="post-title">
              {{ post.title }}
            </h2>
            <h3 class="post-subtitle">
              {{post.content|slice:":200" }}
            </h3>
          </a>
          <p class="post-meta">Posted by {{ post.author }} | {{ post.created_on}} </p>
        </div>
        <hr>
    {% endfor %}  

<div class="clearfix">
 {% if post_list.has_other_pages %}
   <nav aria-label="Page navigation conatiner">
   <ul class="pagination justify-content-center">
  {% if post_list.has_previous %}
  <li><a href="?page={{ post_list.previous_page_number }}" class="page-link">« PREV </a></li>
  {% endif %}
  {% if post_list.has_next %}
  <li><a href="?page={{ post_list.next_page_number }}" class="page-link"> NEXT »</a></li>
    {% endif %}
   </ul>
   </nav>
  {% endif %}
</div>
</div>
{% endblock %}
 
#models.py
from django.db import models
 
from django.contrib.auth.models import User
from django.utils.text import slugify

STATUS = (
    (0,"Draft"),
    (1,"Publish")
)

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='myapp_post')
    updated_on = models.DateTimeField(auto_now= True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)
 
    class Meta:
        ordering = ['-created_on']

    def __str__(self):
        return self.title
  
    class Meta:  
        db_table = "myapp_post"
  
    def save(self, *args, **kwargs):
        value = self.title
        self.slug = slugify(value, allow_unicode=True)
        super().save(*args, **kwargs)

Related Post