我是Django的新手,并尝试根据URL中的不同值设置分页。
在views.py
中class PageListView(ListView):
model = FbPage
paginate_by = 50
all_pages = False
def dispatch(self, *args, **kwargs):
self.request.session['all_pages'] = self.all_pages
return super(PageListView, self).dispatch(*args, **kwargs)
在网址中:
url(r'^$', PageListView.as_view(), name='show_page_list'),
url(r'^all/$', PageListView.as_view(all_pages=True), name='all_show_page_list'),
在模板中:
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
<a href="{% url 'show_page_list' %}?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} (total {{ page_obj.paginator.count }} items).
</span>
{% if page_obj.has_next %}
<a href="{% url 'show_page_list' %}?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</span>
</div>
问题是,即使我在home/all
页面,它也会链接回home
页面分页,因为我通过了show_page_list
而不是all_show_page_list
如何在模板中设置if else以便我可以正确分页,或者我应该做一些不同的事情?
答案 0 :(得分:3)
您可以在上下文变量中定义模式名称,并将其传递到{% url %}
标记:
<div>
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
<a href="{% url list_url %}?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} (total {{ page_obj.paginator.count }} items).
</span>
{% if page_obj.has_next %}
<a href="{% url list_url %}?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</span>
</div>
在你看来:
class PageListView(ListView):
model = FbPage
paginate_by = 50
all_pages = False
def dispatch(self, *args, **kwargs):
self.request.session['all_pages'] = self.all_pages
return super(PageListView, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(PageListView, self).get_context_data(**kwargs)
context['list_url'] = 'all_show_page_list' if self.all_pages else 'show_page_list'
return context