在 Django 中同时对对象进行排序和分页;分页后排序被重置
Sorting and paginating object at the same time in django; after paginating the sort gets reset
如果我对我的壁纸应用了排序,之后如果我尝试分页,排序将被重置。
就像我根据发布日期按升序对壁纸进行排序并在分页后恢复正常。
查看
def home(request):
WAllPAPER_PER_PAGE = 4
WALL = Wallpaper.objects.all()
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Q
ordering =request.GET.get('ordering', "")
search = request.GET.get('search', "")
if search:
wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) |
Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search))
else:
wallpapers = Wallpaper.objects.all()
if ordering:
wallpapers = wallpapers.order_by(ordering)
page = request.GET.get('page', 1)
wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE)
try:
wallpapers = wallpaper_paginator.page(page)
except EmptyPage:
wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages)
except:
wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE)
context = {"wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL}
return render(request, "Wallpaper/Home.html", context)
分页代码
{% if is_paginated %}
<nav class="pagination" >
<ul class="pagination" id="Pagination-list" >
{% if page_obj.has_previous %}
<li class="page-item" >
<a class="page-link" tabindex="-1" aria-disabled="true"
href="/?page={{ page_obj.previous_page_number }}">Previous</a>
</li>
{% endif %}
{% for i in paginator.page_range %}
{% if i == page_obj.number%}
<li class="page-item active" aria-current="page">
<a class="page-link" href="/?page={{i}}" span class="visually-hidden">{{i}}</span></a>
</li>
{% else %}
<li class="page-item" id="{{i}}" value="{{i}}"><a class="page-link" href="/?page={{i}}">{{i}}</a></li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" tabindex="-1" href="/?page={{ page_obj.next_page_number }}">Next</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
//Java script for searching and sorting sync
function get(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search)) //location.search give query sling part
return decodeURIComponent(name[1]);
}
if (get('ordering'))
document.getElementById('placeholder').innerHTML = "Sort: " + document.getElementById(get('ordering')).innerHTML;
if (get('page'))
document.getElementById('Pagination-placeholder').innerHTML = "Pagination: " + document.getElementById(get('page')).innerHTML;
function finalurl() {
var url = new URL(window.location.href);
console.log(url)
var search_params = url.searchParams;
console.log(search_params)
search_params.set('ordering', document.getElementById("sort-list").value);
url.search = search_params.toString();
var new_url = url.toString();
console.log(new_url)
return new_url
}
<!-- searching code -->
<form method="GET" action="/" class="d-flex">
<input class="form-control me-2" name="search" id="search" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
<!-- sorting HTML code -->
<select name="sort" id="sort-list" onchange="location = finalurl();" style="margin-left: auto;">
<option value="" id="placeholder" disabled selected hidden>sort</option>
<option id="pub_date" value="pub_date">Recently added</option>
<option id="-pub_date" value="-pub_date">old post</option>
</select>
发生这种情况的原因是因为您“删除”了有关排序和搜索的 URL 参数。您应该每次将这些添加到分页 URLs.
在视图中,您可以为除页面之外的所有参数创建一个查询字符串:
def home(request):
qd = request.GET.copy()
qd.pop('page', None)
<strong>querystring = qd.urlencode()</strong>
# …
context = {<strong>'querystring': querystring</strong>, 'wallpapers': wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL}
return render(request, "Wallpaper/Home.html", context)
然后在模板中,您呈现指向其他页面的链接:
<a href="/?page={{ page_obj.previous_page_number }}<strong>&{{ querystring }}</strong>" class="page-link" tabindex="-1" aria-disabled="true">Previous</a>
这适用于所有 URL 个链接。
如果我对我的壁纸应用了排序,之后如果我尝试分页,排序将被重置。 就像我根据发布日期按升序对壁纸进行排序并在分页后恢复正常。
查看
def home(request):
WAllPAPER_PER_PAGE = 4
WALL = Wallpaper.objects.all()
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Q
ordering =request.GET.get('ordering', "")
search = request.GET.get('search', "")
if search:
wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) |
Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search))
else:
wallpapers = Wallpaper.objects.all()
if ordering:
wallpapers = wallpapers.order_by(ordering)
page = request.GET.get('page', 1)
wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE)
try:
wallpapers = wallpaper_paginator.page(page)
except EmptyPage:
wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages)
except:
wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE)
context = {"wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL}
return render(request, "Wallpaper/Home.html", context)
分页代码
{% if is_paginated %}
<nav class="pagination" >
<ul class="pagination" id="Pagination-list" >
{% if page_obj.has_previous %}
<li class="page-item" >
<a class="page-link" tabindex="-1" aria-disabled="true"
href="/?page={{ page_obj.previous_page_number }}">Previous</a>
</li>
{% endif %}
{% for i in paginator.page_range %}
{% if i == page_obj.number%}
<li class="page-item active" aria-current="page">
<a class="page-link" href="/?page={{i}}" span class="visually-hidden">{{i}}</span></a>
</li>
{% else %}
<li class="page-item" id="{{i}}" value="{{i}}"><a class="page-link" href="/?page={{i}}">{{i}}</a></li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" tabindex="-1" href="/?page={{ page_obj.next_page_number }}">Next</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
//Java script for searching and sorting sync
function get(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search)) //location.search give query sling part
return decodeURIComponent(name[1]);
}
if (get('ordering'))
document.getElementById('placeholder').innerHTML = "Sort: " + document.getElementById(get('ordering')).innerHTML;
if (get('page'))
document.getElementById('Pagination-placeholder').innerHTML = "Pagination: " + document.getElementById(get('page')).innerHTML;
function finalurl() {
var url = new URL(window.location.href);
console.log(url)
var search_params = url.searchParams;
console.log(search_params)
search_params.set('ordering', document.getElementById("sort-list").value);
url.search = search_params.toString();
var new_url = url.toString();
console.log(new_url)
return new_url
}
<!-- searching code -->
<form method="GET" action="/" class="d-flex">
<input class="form-control me-2" name="search" id="search" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
<!-- sorting HTML code -->
<select name="sort" id="sort-list" onchange="location = finalurl();" style="margin-left: auto;">
<option value="" id="placeholder" disabled selected hidden>sort</option>
<option id="pub_date" value="pub_date">Recently added</option>
<option id="-pub_date" value="-pub_date">old post</option>
</select>
发生这种情况的原因是因为您“删除”了有关排序和搜索的 URL 参数。您应该每次将这些添加到分页 URLs.
在视图中,您可以为除页面之外的所有参数创建一个查询字符串:
def home(request):
qd = request.GET.copy()
qd.pop('page', None)
<strong>querystring = qd.urlencode()</strong>
# …
context = {<strong>'querystring': querystring</strong>, 'wallpapers': wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL}
return render(request, "Wallpaper/Home.html", context)
然后在模板中,您呈现指向其他页面的链接:
<a href="/?page={{ page_obj.previous_page_number }}<strong>&{{ querystring }}</strong>" class="page-link" tabindex="-1" aria-disabled="true">Previous</a>
这适用于所有 URL 个链接。