Django Keeping the same filter in pagination

Viewed 63

I looked into the previous questions about this but did not find exactly the answer to my problem as I am not using django-filters.

I am applying filters to a Search Page and I am using pagination. Of course when you move to the next page all filters are reset. I want to be able to include the same filters when we move from page to page. Here is my code:

views.py:

def recherche(request):
filters = {
    'intermediaire__name__icontains': request.POST.get('kw_intemediaire'),
    'assurance__name__icontains': request.POST.get('kw_assurance'),
    'matricule__icontains': request.POST.get('kw_matricule'),
    'numero__icontains' : request.POST.get('kw_numero'),
    'created_by__name__icontains' : request.POST.get('kw_created_by'),
    'date_posted__icontains' : request.POST.get('kw_date_posted'),
}
filters = {k: v for k, v in filters.items() if v}
dossiers = Dossier.objects.filter(**filters)
print(filters)
p = Paginator(dossiers, 10)
page_num = request.GET.get('page', 1)
try:
    dossiers = p.page(page_num)
except EmptyPage:
    dossiers = p.page(1)

context = {
    'dossiers': dossiers,
    'intermediaires': Intermediaire.objects.all(),
    'assurances': Assurance.objects.all(),
}
return render(request, "dashboard/recherche.html", context)

Template:

<div class="pagination">
    {% if dossiers.has_previous %}
    <a href="?page=1">Première page</a>
    <a href="?page={{ dossiers.previous_page_number }}">&laquo;</a>
    {% endif %}
    <p class="active">Page {{ dossiers.number }} sur {{ dossiers.paginator.num_pages }}</p>
    {% if dossiers.has_next %}
    <a href="?page={{ dossiers.next_page_number }}">&raquo;</a>
    <a href="?page={{ dossiers.paginator.num_pages }}">Dernière page</a>
    {% endif %}
  </div>

I want to do this: I did add a print(filters) to the view to see how the filters are being passed, and they print like this: {'assurance__name__icontains': 'RMA Assurance'}. All I want to do is to take this dictionary and extract the different fields and pass them as GET request parameters in the pagination urls. As you can see I don't have one parameter but 6, that can all be applied at the same time.

0 Answers
Related