【发布时间】:2021-07-09 08:10:22
【问题描述】:
我想每页只显示一个项目,但它显示每页中的所有项目,并且在添加新项目后只增加页码。看图片:
这是我的 views.py
def ShowAuthorNOtifications(request):
user = request.user
notifications = filters.NotificationFilter(
request.GET,
queryset=Notifications.objects.all()
).qs
paginator = Paginator(notifications, 1)
page = request.GET.get('page')
try:
response = paginator.page(page)
except PageNotAnInteger:
response = paginator.page(1)
except EmptyPage:
response = paginator.page(paginator.num_pages)
notification_user = Notifications.objects.filter(user=user).count()
Notifications.objects.filter(user=user, is_seen=False).update(is_seen=True)
template_name ='blog/author_notifications.html'
context = {
'notifications': notifications,
'notification_user':notification_user,
'page_obj':response,
}
print("##############",context)
return render(request,template_name,context)
filters.py
import django_filters
from .models import *
class NotificationFilter(django_filters.FilterSet):
class Meta:
model = Notifications
fields = ['notification_type']
models.py:
NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved')
notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250,default="New Comment")
html
{% for notification in notifications %}
{% if notification.notification_type == "New Comment" %}
#my code......
{%endif%}
{%endfor%}
首先我尝试使用这个Function based views pagenations,但得到了相同的结果。它只是添加页码并在每页显示所有项目。
#更新的问题
正如 NKSM 所说,我的 html 模板中缺少 object_list。现在我的问题已经解决了,它每页只显示一个项目,但是如何在分页部分显示页码,如 page1、page2、page3。现在它显示像这样的分页Page 1 of 4. next last » 我想点击页码,它会带我进入页面。
#updated2
我在我的 html 中缺少 page_obj 我的视图上下文。添加page_obj.paginator.page_range 后,它正在工作并显示页码。现在我可以点击页码了。
【问题讨论】:
-
您应该使用 Paginator 的
object_list。请参阅 Django 文档:docs.djangoproject.com/en/dev/topics/pagination/#example -
点赞:
paginator = Paginator(notifications, 1); cur_page = paginator.page(1); for item in cur_page.object_list -
NKSM 感谢您的评论。你能以我的代码为例,告诉我在哪里申请吗?
标签: django