I need to create paginator based on data from variable. Variable is just python lists.
views.py:
def test(request):
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="pc", # your username
passwd="3346378", # your password
db="mc")
cur = db.cursor()
cur.execute('''SELECT * FROM hello left join hell on hello.Id=hell.Id ''')
row = cur.fetchall()
So, row is lot's of lists. And how can I load it into paginator?
Or one way is to create table and model for data and work with it using Django ORM or something?
Django has built in Paginator class you can check this out: paginator objects and a few examples here: Pagination examples, to use in a view : Using Pagination in view
if it is referencing muliple objects then write plural variable names: so it is rows instead of row
So in your case in the view:
paginator = Paginator(rows, 25) # Show 25 rows per page
page = request.GET.get('page')
rows = paginator.get_page(page)
return render(request, 'example.html', {'rows': rows})
And in HTML:
{% for r in rows %}
{{ r }}<br>
...
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if rows.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ rows.number }} of {{ rows.paginator.num_pages }}.
</span>
{% if rows.has_next %}
next
last »
{% endif %}
</span>
</div>
Related
I'm making a portfolio project where I'm using the Google Books API to do a books search, and the Django Paginator class to paginate the results. I've been able to get search results using a CBV FormView and a GET request, but I can't seem to figure out how to get pagination working for the API response.
The solution I can think of is to append &page=1 to the url of the first search, then pull that param on every GET request and use that to paginate. The problem is, I can't figure out how to append that param on the first search, and I don't know how I'd increment that param value when clicking the pagination buttons.
Here's what I've got now:
Form:
class SearchForm(forms.Form):
search = forms.CharField(label='Search:', max_length=150)
View:
class HomeView(FormView):
template_name = "home.html"
form_class = SearchForm
pageIndex = 0
def get(self, request, *args, **kwargs):
# get submitted results in view and display them on results page. This will be swapped out for an AJAX call eventually
if "search" in request.GET:
# getting search from URL params
search = request.GET["search"]
kwargs["search"] = search
context = super().get_context_data(**kwargs)
# Rest API request
response = requests.get(
f'https://www.googleapis.com/books/v1/volumes?q={search}&startIndex={self.pageIndex}&key={env("BOOKS_API_KEY")}'
)
response = response.json()
items = response.get("items")
# pagination...needs work
paginator = Paginator(items, 2)
page_obj = paginator.get_page(1)
context["results"] = page_obj
return self.render_to_response(context)
else:
return self.render_to_response(self.get_context_data())
Template:
{% extends "base.html" %}
{% block content %}
<form action="/">
{{ form }}
<input type="submit" value="Submit">
</form>
<h1>Books</h1>
<ul>
{% for result in results %}
<li>{{ result.volumeInfo.title }} : {{result.volumeInfo.authors.0}}</li>
{% empty %}
<li>Search to see results</li>
{% endfor %}
</ul>
{% if results %}
<div class="pagination">
<span class="step-links">
{% if results.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ results.number }} of {{ results.paginator.num_pages }}
</span>
{% if results.has_next %}
next
last »
{% endif %}
</span>
</div>
{% endif %}
{% endblock content %}
I also looked at Django REST Framework for this, but the Google Books API response doesn't contain any info on next page, previous page, etc. I've done this kind of pagination in React and it's not difficult, I'm just having trouble adjusting my mental model for how to do this to Django. If anyone could offer some advice on how to make this work, I'd be very grateful.
I have tabs in a Django template displaying the tour packages category. For a single page, I am able to implement pagination in Django, but I do not know how to make pagination based on tabs. Any suggestions on how to filter in Django views based on tabbed heading?
In a single page, I am using it like so:
models.py:
def blog(request):
blog_list = Blog.objects.filter(blog_verification=True)
paginator = Paginator(blog_list, 6) # Show 6 blogs per page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {'blogs': page_obj, 'packages': Packages.objects.all()}
return render(request, 'user/blog.html', context)
Templates:
<div class="pagination">
<span class="step-links">
{% if blogs.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ blogs.number }} of {{ blogs.paginator.num_pages }}.
</span>
{% if blogs.has_next %}
next
last »
{% endif %}
</span>
</div>
I am using django as backend for website
There will be 10 qwestions
i want to paginate them (one qwestion's ans is given then go to next so on ) and atlast give marks calculated based on all the answers given
Any hints on how to do it?
I found somthing similar but dont know how to implement in django
What's the most efficient way to calculate a running total/balance when using pagination (PHP, MySQL)
Have you looked to Django Pagination docs?
https://docs.djangoproject.com/en/2.1/topics/pagination/
From that page
Your view:
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
def listing(request):
contact_list = Contacts.objects.all()
paginator = Paginator(contact_list, 25) # 25 is the items per page, in Your case would be 1
page = request.GET.get('page')
contacts = paginator.get_page(page)
return render(request, 'list.html', {'contacts': contacts})
Your template:
{% for contact in contacts %}
{# Each "contact" is a Contact model object. #}
{{ contact.full_name|upper }}<br>
...
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if contacts.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
next
last »
{% endif %}
</span>
</div>
To go to a page you should add to the url ?page=1 where 1 is the page number.
I follow this Document of djangoproject.com : https://docs.djangoproject.com/en/1.8/topics/pagination/. But it is too simple. It is only Next and Previous button.
Now I want create pagination with more features such as http://i.imgur.com/ZiFeAqG.jpg.
This is code:
View.py
def hire(request):
hire_article_list = hire_article.objects.all().order_by('-id')
#hire_article_list = hire_article.objects.order_by("-publication_date")
paginator = Paginator(hire_article_list, 2) # Show 25 contacts per page
page = request.GET.get('page')
try:
hire_article_s = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
hire_article_s = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
hire_article_s = paginator.page(paginator.num_pages)
#return render_to_response('hire/list.html', {"page_list": page_list})
context = {'hire_article_s': hire_article_s}
return render(request, 'hire/list.html', context)
list.html
{% for j in hire_article_s %}
{# Each "j" is a page_list model object. #}
<li>{{ j.hiring}}</li>
{% endfor %}
{% if hire_article_s.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ hire_article_s.number }} of {{ hire_article_s.paginator.num_pages }}.
</span>
{% if hire_article_s.has_next %}
next
{% endif %}
</span>
</div>
I had a similar need last week and found this super useful gist (https://gist.github.com/jsatt/8183993) that worked fine (though I'm not sure why it wouldn't work till I put request in the function parameters). It's a subclass of django's Paginator function. You could put this in a utility file and call it whenever you want to use Paginate with the range.
For instance, I had mine in a file called utils.py, which is in my core app.
views.py
from core.utils import paginate
def hire(request):
hire_article_list = hire_article.objects.all().order_by('-id')
'''
Show 25 contacts per page, with a page range of 5, which means if you are
on page 8, it shows links to pages 6,7,8,9,10.
'''
hire_article_s = paginate(request, hire_article_list, 25, 5)
context = {'hire_article_s': hire_article_s}
return render(request, 'hire/list.html', context)
list.html
{% if hire_article_s.has_previous %}
previous
{% endif %}
{% for range in hire_article_s.neighbor_range %}
{% if range == hire_article_s.number %}
<li class="pagination__item active ">{{ range }}</li>
{% else %}
<li class="{% if range == hire_article_s.number %}active {% endif %}">{{ range }}</li>
{% endif %}
{% endfor %}
{% if hire_article_s.has_next %}
next
{% endif %}
Hope this helps.
UPDATE
The above code has been edited a bit. I've added the context and the template format. Note that I'm using a loop to go through {{ hire_article_s.neighbor_range }} and print out the page numbers. I also do a check to highlight the current page's number. the This should work, as it's pretty much my own code with your own variable names.
I'm trying to display all the data assoicated to every person and every house on an single template each with pagination.
The problem is everytime I view the entries of a particular data using pagination example person. The other pagination called house get reseted.
For example if I am on page 3 for house and I try to view other entries for page person . The house pagination will get reset back to 1. How do I fix this pagination conflict?
models
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100, blank=True)
def __unicode__(self):
return self.name
class House(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
views
def Display(request):
user= User.objects.get(username=request.user)
comment = Person.objects.get(user=user)
posts = House.objects.filter(user=user)
paginator = Paginator(comment, 5)
try: n = int(request.GET.get("n", '1'))
except ValueError: page = 1
try:
comment = paginator.page(n)
except (InvalidPage, EmptyPage):
comment = paginator.page(paginator.num_pages)
paginator = Paginator(posts, 5)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request,'display.html',{'posts':posts,'comment':comment})
HTML
{% for p in posts.object_list %}
{{p.name}}
{% endfor %}
{% if posts.object_list and posts.paginator.num_pages > 1 %}
<div class="pagination" style="margin-top: 20px; margin-left: -20px; ">
Page {{ posts.number }} of {{ posts.paginator.num_pages }}<br>
{% if posts.has_previous %}
<a class="Link" href= "{% if formula %}?text={{formula}}&{% else %}?{% endif %}page={{ posts.previous_page_number }}">newer entries << </a>
{% endif %}
{% if posts.has_next %}
<a class="Link" href="{% if formula %}?text={{formula}}&{% else %}?{% endif %}page={{ posts.next_page_number }}"> >> older entries</a>
{% endif %}
</span>
</div>
{% endif %}
{% for c in comment.object_list %}
{{c.name}}
{% endfor %}
{% if comment.object_list and comment.paginator.num_pages > 1 %}
Page {{ comment.number }} of {{ comment.paginator.num_pages }}
{% if comment.has_previous %}
<a class="Link" href= "?n={{ comment.previous_page_number }}">newer entries << </a>
{% endif %}<br>
{% if comment.has_next %}
<a class="Link" href="?n={{ comment.next_page_number }}"> >> older entries</a>
{% endif %}
</span>
</div>
{% endif %
First off, your variable names versus how you describe everything is quite confusing.
The issue is you are using two different variables for the page: n for person (or comment) and page for house (or posts). In each of your <a href=""> you need to set both n and page not just one. So:
<a class="Link" href= "{% if formula %}?text={{formula}}&{% else %}?{% endif %}page={{ posts.previous_page_number }}&n={{ comment.number }}">newer entries << </a>
<a class="Link" href="{% if formula %}?text={{formula}}&{% else %}?{% endif %}page={{ posts.next_page_number }}&n={{ comment.number }}"> >> older entries</a>
<a class="Link" href= "?n={{ comment.previous_page_number }}&page={{ posts.number }}">newer entries << </a>
<a class="Link" href="?n={{ comment.next_page_number }}&page={{ posts.number }}"> >> older entries</a>
In the same view you change the value of paginator two times
paginator = Paginator(comment, 5)
# here you have code that does stuff and some lines below
paginator = Paginator(posts, 5)
if you want two paginators in the same view you should also name them differently (and add them to your context variables)
Something I can suggest is to have an ajax pagination view that you're going to call to switch between pages in your templates. In this way, you can change page to each resultset separately without needing to reload the entire view (and probably loosing your pagination state)