2 回答

TA貢獻1810條經驗 獲得超4個贊
正如@WillemVanOnsem 指出的那樣,問題不在于視圖,而在于模板中的 URL(templates/pagination/listview.html)。以前,下一個按鈕href="?page={{ page_obj.next_page_number }}"意味著request.GET它只包含用于分頁的頁碼,而不包含其他過濾器和按條件排序。
然后解決方案是附加request.GET.urlencode到href喜歡
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}&{{ request.GET.urlencode }}">Next</a>
但是,這不是一個徹底的解決方案,因為簡單地附加request.GET也會附加您當前所在的頁碼。簡單地說,如果你從第 1 頁跳轉到第 2 頁再到第 3 頁,你最終會得到一個看起來像這樣的 URL
http://localhost:8000/listview/?page=1&page=2&page=3...
這request.GET是一個 QueryDict 之類的<QueryDict: {'page': ['1'], ...}>。對此的解決方案是簡單地彈出page參數,但是,因為request.GET它是不可變的,您首先必須制作它的副本。本質上,我get_context_data在 ListVew 中的方法中添加了以下幾行
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Form List View'
context['filter_form'] = forms.FilterListView(self.request.GET)
get_copy = self.request.GET.copy()
if get_copy.get('page'):
get_copy.pop('page')
context['get_copy'] = get_copy
return context
在模板中,我將get_copy對象稱為href="?page={{ page_obj.next_page_number }}&{{ get_copy.urlencode }}"
對于整個模板示例,請遵循templates/pagination/listview.html
不是最優雅的解決方案,但我覺得它對大多數人來說足夠簡單。

TA貢獻1877條經驗 獲得超6個贊
我遇到了同樣的問題,我通過下面的鏈接解決了這個問題。
https://www.caktusgroup.com/blog/2018/10/18/filtering-and-pagination-django/
添加回答
舉報