在Django CBV (ListView)中,使用GET方法提交带有filter_1和filter_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 %}发布于 2019-02-21 22:21:46
我是这样做的
@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>https://stackoverflow.com/questions/54808110
复制相似问题