David Dahan
David Dahan

Reputation: 11162

Django: Combining search view with Pagination

In a Django CBV (ListView), after submitting a form using GET method, with filter_1 and filter_2 fields, the resulting URL I get is something like:

http://example.com/order/advanced-search?filter_1=foo&filter_2=bar

Everything is ok. However, I'd like to use pagination, proving to my template a URL like:

http://example.com/order/advanced-search?page=2&filter_1=foo&filter_2=bar

Let's say I could override this method for this purpose:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['my_form_values'] = self.request.GET

Now, how can I use my_form_values in my pagination template to display the right URLs?

For now, here is my (simplified) pagination template code:

{% for num in page_obj.page_range %}
    {% if page_obj.number == num %}
        <li class="page-item active">
            <span class="page-link">{{ num }}</span>
        </li>
    {% else %}
        <li class="page-item">
            <a class="page-link" href="?page={{ num }}">{{ num }}</a>
        </li>
    {% endif %}
{% endfor %}

Upvotes: 0

Views: 364

Answers (1)

pfitzer
pfitzer

Reputation: 86

I do it this way

@register.simple_tag(takes_context=True)
def param_replace(context, **kwargs):
    d =context['request'].GET.copy()
    for k,v in kwargs.items():
        d[k] = v
    for k in [k for k,v in d.items() if not v]:
        del d[k]
    return d.urlencode()

and then the pagination in template

<ul class="pagination">
    {% if page_obj.has_previous %}
        <li class="page-item"><a class="page-link"
                                 href="?{% param_replace page=1 %}">{% trans 'first' %}</a>
        </li>
        <li class="page-item"><a class="page-link"
                                 href="?{% param_replace page=page_obj.previous_page_number %}">{{ page_obj.previous_page_number }}</a>
        </li>
    {% endif %}
    <li class="page-item active"><a class="page-link"
                                    href="?{{ page_obj.number }}">{{ page_obj.number }}</a>
    </li>
    {% if page_obj.has_next %}
        <li class="page-item"><a class="page-link"
                                 href="?{% param_replace page=page_obj.next_page_number %}">{{ page_obj.next_page_number }}</a>
        </li>
        <li class="page-item"><a class="page-link"
                                 href="?{% param_replace page=page_obj.paginator.num_pages %}">{% trans 'last' %}</a>
        </li>
    {% endif %}
</ul>

Upvotes: 1

Related Questions