Thursday, 2 March 2017

Paginating in Django

This is a example of  Paginating in Django with Screen Shoot.


Create a project mysite .
Create a app called own.


mysite/urls.py:

from django.conf.urls import include, url


urlpatterns = [
    url(r'^own/', include('own.urls',namespace='own')),
    url(r'^h/$', h,name='h'),
]


mysite/views.py:

from django.shortcuts import render
from django.shortcuts import render_to_response,redirect,get_object_or_404
from django.contrib.auth import login,authenticatefrom own.models import *
from own/models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def h(request):
        names_list=Name.objects.all()
        page = request.GET.get('page', 1)
        paginator = Paginator(names_list, 10)
        try:
                names = paginator.page(page)
        except PageNotAnInteger:
                users = paginator.page(1)
        except EmptyPage:
                users = paginator.page(paginator.num_pages)
        return render_to_response('1.html',{'names':names})

own/models.py:

from django.db import models
from django.contrib.auth.models import User

class  Name(models.Model):
        name=models.CharField(max_length=20)

        def __str__(self):
                return self.name


Template/1.html:

<table class="table table-bordered">
  <thead>
    <tr>
      <th>Names</th>

    </tr>
  </thead>
  <tbody>
    {% for name in names %}
      <tr>
        <td>{{ name }}</td>

      </tr>
    {% endfor %}
  </tbody>
</table>


   {% if names.has_previous %}
      <a href="?page={{ names.previous_page_number }}">&laquo;</a>
    {% else %}
      <span>&laquo;</span>
    {% endif %}
    {% for i in names.paginator.page_range %}
      {% if names.number == i %}
        <span>{{ i }} <span class="sr-only">(current)</span></span>
      {% else %}
        <a href="?page={{ i }}">{{ i }}</a>
      {% endif %}
    {% endfor %}
    {% if names.has_next %}
      <a href="?page={{ names.next_page_number }}">&raquo;</a>
    {% else %}
      <span>&raquo;</span>
{% endif %}


Bellow is the SS:











Add me in Facebook HERE.


No comments:

Post a Comment

Popular Posts