Abhijeet Pal: Adding Pagination With Django

While working on a modern web application quite often you will need to paginate the app be it for better user experience or performance. Fortunately, Django comes with built-in pagination classes for managing paginating data of your application.

In this article, we will go through the pagination process with class-based views and function based views in Django.

Prerequisite

For the sake of this tutorial I am using a blog application  – Github repo

The above project is made on Python 3.7, Django 2.1 and Bootstrap 4.3. This is a very basic blog application displaying a list of posts on the homepage but when the number of posts increases we need to split them up.

Recommended Article:  Building A Blog Application With Django

Adding Pagination Using Class-Based-Views [ ListView ]

The Django ListView class comes with built-in support for pagination so all we need to do is take advantage of it. Pagination is controlled by the GET parameter that controls which page to show.

First, open the views.py file of your app.

from django.views import generic from .models import Post   class PostList(generic.ListView):     queryset = Post.objects.filter(status=1).order_by('-created_on')     template_name = 'index.html'  class PostDetail(generic.DetailView):     model = Post     template_name = 'post_detail.html' 

Now in the PostList view we will introduce a new attribute paginate_by which takes an integer specifying how many objects should be displayed per page. If this is given, the view will paginate objects with paginate_by objects per page. The view will expect either a page query string parameter (via request.GET) or a page variable specified in the URLconf.

class PostList(generic.ListView):     queryset = Post.objects.filter(status=1).order_by('-created_on')     template_name = 'index.html'     paginate_by = 3

Now our posts are paginated by 3 posts a page.

Next, to see the pagination in action, we need to edit the template which for this application is the index.html file paste the below snippet.

{% if is_paginated %}   <nav aria-label="Page navigation conatiner"></nav>   <ul class="pagination justify-content-center">     {% if page_obj.has_previous %}     <li><a href="?page={{ page_obj.previous_page_number }}" class="page-link">&laquo; PREV </a></li>     {% endif %}     {% if page_obj.has_next %}     <li><a href="?page={{ page_obj.next_page_number }}" class="page-link"> NEXT &raquo;</a></li>      {% endif %}   </ul>   </nav> </div> {% endif %}

Note that we are using Bootstrap 4.3 for this project, if you are using any other frontend framework you may change the classes.

Now run the server and visit http://127.0.0.1:8000/ you should see the page navigation buttons below the posts.

Adding pagination with class based views in django

 

Adding Pagination Using Function-Based-Views

Equivalent function based view for the above PosList class would be.

def PostList(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}) 

So in the view, we instantiate the Paginator class with the number of objects to be displayed on each page i.e 3. Then we have the request.GET.get('page') parameter which returns the current page number. The page() method is used to obtain the objects from the desired page number. Below that we have two exception statements for PageNotAnInteger and EmptyPage both are subclasses of InvalidPage finally at the end we are rendering out the HTML file.

Now in your templates paste the below snippet.

{% if post_list.has_other_pages %}   <nav aria-label="Page navigation conatiner"></nav>   <ul class="pagination justify-content-center">     {% if post_list.has_previous %}     <li><a href="?page={{ post_list.previous_page_number }}" class="page-link">&laquo; PREV </a></li>     {% endif %}     {% if post_list.has_next %}     <li><a href="?page={{ post_list.next_page_number }}" class="page-link"> NEXT &raquo;</a></li>   </ul>   </nav>   {% endif %}

Save the files and run the server you should see the NEXT button below the post list.

Adding Pagination Using Function-Based-Views

The post Adding Pagination With Django appeared first on Django Central.

Planet Python

EuroPython: EuroPython 2019: Conference and training ticket sale opens today

We will be starting the EuroPython 2019 conference and training ticket sales

today (Monday) at 12:00 CEST.

image

https://ep2019.europython.eu/registration/buy-tickets/

Only 300 training tickets available

After the rush to the early-bird tickets last week (we sold more than 290 tickets in 10 minutes), we expect a rush to the regular and training tickets this week as well.

We only have 300 training tickets available, so if you want to attend the training days, please consider getting your ticket soon.

Available ticket types

We will have the following ticket types available:

  • regular conference tickets – admission to the conference days (July 10-12) and sprints (July 13-14)
  • training tickets – admission to the training days (July 8-9)
  • combined tickets – admission to training, conference and sprint days (July 8-14)

Please see our registration page for full details on the available tickets.

As reminder, here’s the conference layout:

  • Monday & Tuesday, July 8 & 9: Trainings, Beginners’ Day and other workshops
  • Wednesday–Friday, July 10–12: Conference talks, keynotes & exhibition
  • Saturday & Sunday, July 13 & 14: Sprints

Combined Tickets

These are a new ticket type we are introducing for EuroPython 2019, to simplify purchase and check-in at the conference for attendees who want to attend the complete EuroPython 2019 week with a single ticket.

To make the ticket more attractive, we are granting a small discount compared to purchasing training and conference tickets separately.

Enjoy,

EuroPython 2019 Team
https://ep2019.europython.eu/
https://www.europython-society.org/

Planet Python

Podcast.__init__: Hardware Hacking Made Easy With CircuitPython

Summary

Learning to program can be a frustrating process, because even the simplest code relies on a complex stack of other moving pieces to function. When working with a microcontroller you are in full control of everything so there are fewer concepts that need to be understood in order to build a functioning project. CircuitPython is a platform for beginner developers that provides easy to use abstractions for working with hardware devices. In this episode Scott Shawcroft explains how the project got started, how it relates to MicroPython, some of the cool ways that it is being used, and how you can get started with it today. If you are interested in playing with low cost devices without having to learn and use C then give this a listen and start tinkering!

Announcements

  • Hello and welcome to Podcast.__init__, the podcast about Python and the people who make it great.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With 200 Gbit/s private networking, scalable shared block storage, node balancers, and a 40 Gbit/s public network, all controlled by a brand new API you’ve got everything you need to scale up. And for your tasks that need fast computation, such as training machine learning models, they just launched dedicated CPU instances. Go to pythonpodcast.com/linode to get a $ 20 credit and launch a new server in under a minute. And don’t forget to thank them for their continued support of this show!
  • You listen to this show to learn and stay up to date with the ways that Python is being used, including the latest in machine learning and data analysis. For even more opportunities to meet, listen, and learn from your peers you don’t want to miss out on this year’s conference season. We have partnered with organizations such as O’Reilly Media, Dataversity, and the Open Data Science Conference. Go to pythonpodcast.com/conferences to learn more and take advantage of our partner discounts when you register.
  • Visit the site to subscribe to the show, sign up for the newsletter, and read the show notes. And if you have any questions, comments, or suggestions I would love to hear them. You can reach me on Twitter at @Podcast__init__ or email hosts@podcastinit.com)
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers
  • Join the community in the new Zulip chat workspace at pythonpodcast.com/chat
  • Your host as usual is Tobias Macey and today I’m interviewing Scott Shawcroft about CircuitPython, the easiest way to program microcontrollers

Interview

  • Introductions
  • How did you get introduced to Python?
  • Can you start by explaining what CircuitPython is and how the project got started?
    • I understand that you work at Adafruit and I know that a number of their products support CircuitPython. What other runtimes do you support?
  • Microcontrollers have typically been the domain of C because of the resource and performance constraints. What are the benefits of using Python to program hardware devices?
  • With the wide availability of powerful computing platforms, what are the benefits of experimenting with microcontrollers and their peripherals?
  • I understand that CircuitPython is a friendly fork of MicroPython. What have you changed in your version?
    • How do you structure your development to avoid conflicts with the upstream project?
    • What are some changes that you have contributed back to MicroPython?
  • What are some of the features of CircuitPython that make it easier for users to interact with sensors, motors, etc.?
  • CircuitPython provides an easy on-ramp for experimenting with hardware projects. Is there a point where a user will outgrow it and need to move to a different language or framework?
  • What are some of the most interesting/innovative/unexpected projects that you have seen people build using CircuitPython?
    • Are there any cases of someone building and shipping a production grade project in CircuitPython?
  • What have been some of the most interesting/challenging/unexpected aspects of building and maintaining CircuitPython?
  • What is in store for the future of the project?

Keep In Touch

Picks

Links

The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA


Planet Python

Weekly Python StackOverflow Report: (clxxviii) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2019-05-19 10:39:17 GMT


  1. Slice a list based on an index and items behind it in Python – [20/16]
  2. pylint protection again self-assignment – [14/2]
  3. Filter a data-frame and add a new column according to the given condition – [11/5]
  4. Understanding Python syntax in lists vs series – [9/3]
  5. How to subset row of condition with some of N rows before the condition meet , more faster than my code? – [8/1]
  6. How to generate a time-ordered uid in Python? – [7/2]
  7. Creating an order-preserving multi-value dict for Django – [7/1]
  8. Update elements of dataframe by applying function involving same row elements – [6/6]
  9. Construct new column with first row of a groupby with two columns – Pandas – [6/4]
  10. Do JavaScript classes have a method equivalent to Python classes’ __call__? – [6/3]

Planet Python