Django:将搜索视图与分页相结合

时间:2019-02-21 13:20:09

标签: python django django-class-based-views django-pagination

在Django CBV(ListView)中,使用GET方法提交具有filter_1filter_2字段的表单后,得到的结果URL类似于:

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

一切都很好。 但是,我想使用分页,向我的模板证明一个URL,如:

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

假设我可以为此目的重写此方法:

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

现在,如何在分页模板中使用my_form_values来显示正确的URL?

现在,这是我的(简化的)分页模板代码:

{% 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 %}

1 个答案:

答案 0 :(得分:0)

我是这样的

@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()

,然后在模板中分页

<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>