Daily Dev Notes 2024/06/06

Finally managed to get around to implementing Pagination. This was the first time in a long time that I've had to implement pagination, so I was pretty much starting from scratch.

Thankfully, the docs are good, and the following two pages on the Django docs site provided all the info I needed:

Still took me a while to get the right mental model of how this works. In simple terms, you create a Paginator object by passing it a queryset, e.g. Paginator(Post.post_objects.get_published_posts(), 20, with the number 20 indicating how many objects per page. The Paginator object consists of one or more "pages" which are Page object types. To get the Page you need, you call the get_page() method and pass it an integer or None. If you pass it None it will return the first page, or if you specify a number, it will retrieve that page from the Paginator object. To get the page number, the easiest way is to use a query string parameter, e.g. page_number = request.GET.get("page"). If page doesn't exist in the query string, then it returns None which in turn would retrieve the first Page from the Paginator object.

Then you pass the Page object to the template in the context, and from there you can access the methods to build a navigation menu. I won't repeat that here because there's a great example on the Django docs.

While I was in the views file, I also added some better docstrings, and moved some date validation code into the utils file. Now I only have views in the views.py file!

This is going to cause another breaking change to DJ Press, so I didn't update the package yet. I have some more changes to make over the weekend, so will wait to include those too.