Last active
November 24, 2023 08:43
-
-
Save luxcem/ac4a3a0e3115f4309b4755fa91d94b42 to your computer and use it in GitHub Desktop.
Django quick and simple table pagination and sorting.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<table class="table"> | |
<tr> | |
<th>{% ordering_link "pk" "#" %}</th> | |
<th>{% ordering_link "name" "Nom" %}</th> | |
</tr> | |
{% for item in page_obj %} | |
<tr> | |
<td>{{ item.pk }}</td> | |
<td>{{ item.name }}</td> | |
{% endfor %} | |
</table> | |
<nav> | |
<ul class="pagination pagination-sm justify-content-center"> | |
{% if page_obj.has_previous %} | |
<li class="page-item"> | |
<a class="page-link" href="?page=1">«</a> | |
</li> | |
<li class="page-item"> | |
<a class="page-link" href="?page={{ page_obj.previous_page_number }}">{% trans "Prev" %}</a> | |
</li> | |
{% endif %} | |
<li class="page-item active" aria-current="page"> | |
<a class="page-link" href="#">{{ page_obj.number }}</a> | |
</li> | |
{% if page_obj.has_next %} | |
<li class="page-item"> | |
<a class="page-link" href="?page={{ page_obj.next_page_number }}">{% trans "Next" %}</a> | |
</li> | |
<li class="page-item"> | |
<a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">»</a> | |
</li> | |
{% endif %} | |
</ul> | |
</nav> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def list_view(request: HttpRequest) -> HttpResponse: | |
ordering = request.GET.get("order_by", "name") | |
# Optionaly filter ordering with an allow list | |
page_number = request.GET.get("page") or 1 | |
object_list = MyModel.objects.all().order_by(ordering) | |
paginator = Paginator(object_list, 10) | |
return render( | |
request, | |
"list.html", | |
{ | |
"paginator": paginator, | |
"page_obj": paginator.page(page_number), | |
}, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment