Рефакторинг пагинации через custom template tag url_replace

- Создан элегантный тег для автоматического сохранения GET-параметров
- Код пагинации сократился в 10 раз
- Переиспользуется в любых шаблонах проекта
- 100 процентов Django-way без хаков
This commit is contained in:
2026-01-03 15:19:47 +03:00
parent f1f44a93b2
commit 36cca23b60
3 changed files with 39 additions and 5 deletions

View File

@@ -1,4 +1,5 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load query_tags %}
{% block title %}Клиенты{% endblock %} {% block title %}Клиенты{% endblock %}
@@ -132,12 +133,12 @@
<ul class="pagination pagination-sm justify-content-center mb-0"> <ul class="pagination pagination-sm justify-content-center mb-0">
{% if page_obj.has_previous %} {% if page_obj.has_previous %}
<li class="page-item"> <li class="page-item">
<a class="page-link" href="?page=1{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.has_notes %}&has_notes=on{% endif %}{% if request.GET.no_phone %}&no_phone=on{% endif %}{% if request.GET.no_email %}&no_email=on{% endif %}" title="Первая страница"> <a class="page-link" href="{% url_replace page=1 %}" title="Первая страница">
&laquo;&laquo; &laquo;&laquo;
</a> </a>
</li> </li>
<li class="page-item"> <li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.has_notes %}&has_notes=on{% endif %}{% if request.GET.no_phone %}&no_phone=on{% endif %}{% if request.GET.no_email %}&no_email=on{% endif %}" title="Предыдущая"> <a class="page-link" href="{% url_replace page=page_obj.previous_page_number %}" title="Предыдущая">
&laquo; &laquo;
</a> </a>
</li> </li>
@@ -160,7 +161,7 @@
</li> </li>
{% else %} {% else %}
<li class="page-item"> <li class="page-item">
<a class="page-link" href="?page={{ num }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.has_notes %}&has_notes=on{% endif %}{% if request.GET.no_phone %}&no_phone=on{% endif %}{% if request.GET.no_email %}&no_email=on{% endif %}">{{ num }}</a> <a class="page-link" href="{% url_replace page=num %}">{{ num }}</a>
</li> </li>
{% endif %} {% endif %}
{% endif %} {% endif %}
@@ -169,12 +170,12 @@
{% if page_obj.has_next %} {% if page_obj.has_next %}
<li class="page-item"> <li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.has_notes %}&has_notes=on{% endif %}{% if request.GET.no_phone %}&no_phone=on{% endif %}{% if request.GET.no_email %}&no_email=on{% endif %}" title="Следующая"> <a class="page-link" href="{% url_replace page=page_obj.next_page_number %}" title="Следующая">
&raquo; &raquo;
</a> </a>
</li> </li>
<li class="page-item"> <li class="page-item">
<a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}{% if request.GET.has_notes %}&has_notes=on{% endif %}{% if request.GET.no_phone %}&no_phone=on{% endif %}{% if request.GET.no_email %}&no_email=on{% endif %}" title="Последняя страница"> <a class="page-link" href="{% url_replace page=page_obj.paginator.num_pages %}" title="Последняя страница">
&raquo;&raquo; &raquo;&raquo;
</a> </a>
</li> </li>

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
"""
Custom template tags для работы с URL и query параметрами
"""
from django import template
from django.http import QueryDict
register = template.Library()
@register.simple_tag(takes_context=True)
def url_replace(context, **kwargs):
"""
Создаёт URL с сохранением всех текущих GET-параметров,
заменяя или добавляя переданные параметры.
Использование:
{% url_replace page=2 %}
{% url_replace page=num has_notes='' %} {# Удаление параметра #}
Автоматически сохраняет все существующие GET-параметры (q, has_notes, no_phone и т.д.)
"""
query = context['request'].GET.copy()
for key, value in kwargs.items():
if value == '' or value is None:
# Удаляем параметр если значение пустое
query.pop(key, None)
else:
query[key] = value
return f"?{query.urlencode()}" if query else "?"