Django Pagination: Loads all elements from first page - python

I have a page blog.html, and pagination sequence loads just fine, but I query the paginator to show one element on a page to test if pagination works. I have 4 items in the DB, the pagination reads 4 elements, but shows all elements on all pages.
views.py
def blog(request):
blog_cat = Blog_Categorie.objects.all()
all_blog = Blog.objects.all()
page = request.GET.get('page')
paginator = Paginator(all_blog, 1)
try:
blog = paginator.page(page)
except PageNotAnInteger:
blog = paginator.page(1)
except EmptyPage:
blog = paginator.page(paginator.num_pages)
return render_to_response('blog.html',
'blog':all_blog,'blog_cat':blog_cat,'blog_p':blog})
blog.html
<div class="col-lg-12 col-md-12 text-center">
{% if blog_p.has_other_pages %}
<ul class="pagination">
{% if blog_p.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in blog_p.paginator.page_range %}
{% if blog_p.number == i %}
<li class="active"><span>{{ i }}</span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if blog_p.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>

Seems you are iterating over blog_p.paginator.page_range. Do iterate over blog_p.
For doc

Related

Reverse for 'surveydetails' not found. 'surveydetails' is not a valid view function or pattern name

I've been stuck on this for a while, can't seem to fix the error. I've checked the code a hundred times but obviously there is something I'm missing. I have installed my app also.
Can anybody see what I'm missing?
views.py
def survey_details(request, id=None):
context = {}
surveys = Survey.objects.get(id=id)
context['survey'] = survey
return render(request, 'surveydetails.html', context)
feedback.urls.py
path('details/<int:id>', views.survey_details, name="surveydetails"),
surveys.html
{% extends 'main.html' %}
{% block content%}
<h1>Surveys</h1>
<h2>list of {{title}} </h2>
{% if surveys %}
<ul>
{% for survey in surveys %}
<li>
{{ survey.title }}
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no surveys.</p>
{% endif %}
{% endblock %}
surveydetails.html
{% extends 'main.html' %}
{% block content%}
<h1>Surveys</h1>
<h2>Detail page</h2>
<h3>{{question.title}}</h3>
<p>Details page of {{question.title}}</p>
{% endblock %}
Here you are not passing the survey id.
{% for survey in surveys %}
<li>
{{ survey.title }}
</li>
{% endfor %}

Pagination stopped working on Django application

I am new to Django and I just picked up a book "Django 2 by example". I followed all the code in the tutorial bu something broke the pagination along the line and I just can't figure what it is. I get an output of "Page of ." instead of "Page 1 of 1. at the base of my blog. Find some of my code below:. P.S: Kindly ignore the indentation in the code. Thank you.
Views.py
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from django.core.mail import send_mail
from django.db.models import Count
from taggit.models import Tag
from .models import Post, Comment
from .forms import EmailPostForm, CommentForm
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None`
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3) # 3 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request,
'blog/post/list.html',
{'page': page,
'posts': posts,
'tag' : tag})
list.html
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% if tag %}
<h2>Posts tagged with "{{ tag.name }}"</h2>
{% endif %}
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="tags">
Tags:
{% for tag in post.tags.all %}
<a href="{% url "blog:post_list_by_tag" tag.slug %}">
{{ tag.name }}
</a>
{% if not forloop.last %}, {% endif %}
{% endfor %}
</p>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% include "pagination.html" with page=page_obj %}
{% endblock %}
Pagination.html (template)
<div class="pagination">
<span class="step-links">
{% if page.has_previous %}
Previous
{% endif %}
<span class="current">
Page {{ page.number }} of {{ page.paginator.num_pages}}.
</span>
{% if page.has_next %}
Next
{% endif %}
</span>
</div>

search data for table template by django.can't not show next page >

i'm create template for search this table.it can search but click for next page is error in the picture
For Error
Same mycode.
#view.py
def search(request):
query = request.GET.get('q1')
qselect = request.GET.get('q2')
qs = Record_data.objects.filter(Q(invoice_no__startswith=query) | Q(product=query))
page = request.GET.get('page', 1)
paginator = Paginator(qs, 5)
try:
page1 = paginator.page(page)
except PageNotAnInteger:
page1 = paginator.page(1)
except EmptyPage:
page1 = paginator.page(paginator.num_pages)
template_name = 'status.html'
context = {'object_list': page1}
#
page function
#html code
{% if object_list.has_other_pages %}
<ul class="pagination">
{% if object_list.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ object_list.previous_page_number }}">Previous</a></li>
{% else %}
<li class="page-item disabled"><span class="page-link">Previous</span></li>
{% endif %}
{% for i in object_list.paginator.page_range %}
{% if object_list.number == i %}
<li class="page-item active"><span class="page-link">{{ i }}</span></li>
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if object_list.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ object_list.next_page_number }}">Next</a></li>
{% else %}
<li class="page-item disabled"><span class="page-link">Next</span></li>
{% endif %}
</ul>
{% endif %}
Rather than hard coding why not use the data tables jquery plugin?
https://datatables.net
use the above links and customise to your use ... i aint marketing but its simple to use a jquery plugin for data tables and hard coding will be easy for whole page Pagination.

Python Flask SQLAlchemy Pagination

I am having trouble implementing pagination with Flask-SQLAlchemy or Flask-Pagination, either or. I am unsure how to initialize the pagination, setting pages, determining pages, offest, etc. I am coming from PHP, quite new to Python.
I am querying all the posts in my database
posts = Posts.query.order_by(Posts.time.desc()).all()
I have been looking at the following examples:
http://www.ergo.io/tutorials/better-pagination-in-flask/better-pagination-in-flask/
https://pythonhosted.org/Flask-paginate/
sqlalchemy pagination
I am confused on really what to do, the information I am finding greatly differs between articles. It's left me with confusion and not knowing where to begin. I want to query all rows of the database table, limit the results to 20 and paginate. I'm not seeing this clearly.
I recommend using Flask-SQLAlchemy's pagination: http://flask-sqlalchemy.pocoo.org/2.1/api/?highlight=pagination#flask.ext.sqlalchemy.Pagination
There's a well-written example here: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination
Here's the basic idea for the view:
#app.route('/myview/<int:page>',methods=['GET'])
def view(page=1):
per_page = 10
posts = Posts.query.order_by(Posts.time.desc()).paginate(page,per_page,error_out=False)
return render_template('view.html',posts=posts)
And then for the template (I don't know your posts model so I made something up):
<html>
<head>
Posts
</head>
<body>
{% for post in posts.items %}
<p>
{{ post.post_name }} post body: <b>{{ post.body }}</b>
</p>
{% endfor %}
{% if posts.has_prev %}<< Newer posts{% else %}<< Newer posts{% endif %} |
{% if posts.has_next %}Older posts >>{% else %}Older posts >>{% endif %}
</body>
</html>
Controller
#app.route('/', methods=['GET'], defaults={"page": 1})
#app.route('/<int:page>', methods=['GET'])
def index(page):
page = page
per_page = 2
users = User.query.paginate(page,per_page,error_out=False)
# print("Result......", users)
return render_template("index.html", users=users)
in the View
{% for user in users.items %}
<h1> {{ user.name }} </h1>
{% endfor %}
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if users.has_prev %}
<li class="page-item"> <a class="page-link" href="{{ url_for('index', page=users.prev_num) }}">Previous</a></li>
{% else %}
<li class="page-item"><a class="page-link btn disabled" href="#">Previous</a></li>
{% endif %}
{% if users.has_next %}
<li class="page-item"> <a class="page-link" href="{{ url_for('index', page=users.next_num) }}">Next</a></li>
{% else %}
<li class="page-item"><a class="page-link btn disabled" href="#">Next</a></li>
{% endif %}
</ul>
</nav>
I used #user3186184 code but I got this error:
TypeError: 'Pagination' object is not iterable
But when I add items to the end of these code:
users = User.query.paginate(page,per_page,error_out=False).items
My issue was fixed.
Here is the simplest answer to add pagination in flask
no_of_posts = 3
page = request.args.get("number")
if page is None:
page = 1
else:
page = int(page)
allPosts = Posts.query.filter_by().all()
length = len(allPosts)
allPosts = allPosts[(page-1)*no_of_posts: page*no_of_posts]
if page > 1:
prev = page -1
else:
prev = None
if page < math.ceil(length/no_of_posts):
next = page + 1
else:
next = None
In the template
{% if prev %}
« Previous
{% endif %}
{% if next %}
Next »
{% endif %}

Error in the template with Django : can I make arithmetic in if statement

I would like to make a pagination with Bootstrap : a new page every 10 new field in data.
file.html
{% for d in data %}
{% if forloop.first %}
<ul class="pagination">
{% endif %}
{% if (forloop.counter % 10) == 0 %}
<li>{{ forloop.counter % 10 }}</li>
{% endif %}
{% if forloop.last %}
</ul>
{% endif %}
{% endfor %}
output I would like that => Bootstrap pagination
But Django give me an error for this :
{% if (forloop.counter % 10) == 0 %}
TemplateSyntaxError :/
I don't know how to do except create my own filter or add a filter, but i would like to know first if i can do in the template first.
PS: I use Django 1.5 and I can't upgrade it.
Edit:
Finally I use this condition:
{% if forloop.counter|divisibleby:'10' and forloop.counter|divisibleby:'5' and forloop.counter|divisibleby:'2' %}
Like that I know when I have a 10 multiple.
The modulus (%) operator is not available in django templates. However, you can use the divisibleby (https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#divisibleby) template filter, something like
{% if forloop.counter|divisibleby:"2" %}
Use the paginator, your QuerySet are not evaluated for the hole table, just the number you need to build the page, and it offers properties that you can use in the template like (page_range, next_page_number, has_next, etc.)
here is the code withe BootStrap 2 and django.core.paginator:
<div class="pagination pagination-centered">
<ul>
{% if MYDATAENTIRES.has_previous %}
<li>
{% trans "Précédent" %}
</li>
{% endif %}
{% for i in MYDATAENTIRES.paginator.page_range %}
<li {% ifequal MYDATAENTIRES.number i %} {{ 'class="disabled"' }} {% endifequal %}>
<a href="?page={{ i }}">
{{ i }}
</a>
</li>
{% endfor %}
{% if MYDATAENTIRES.has_next %}
<li>
{% trans "Suivant" %}
</li>
{% endif %}
</ul>
</div>

Categories