sách gpt4 ai đã đi

Phân trang ở chế độ xem chi tiết

In lại 作者:太空宇宙 更新时间:2023-11-04 02:05:54 27 4
mua khóa gpt4 Nike

我在我的博客中为我的帖子使用了详细 View ,每篇帖子都有评论,所以我想对它们进行分页,但我不知道该怎么做,因为我请求了帖子模型。我知道如何在功能 View 中执行此操作,但不知道如何在详细 View 中执行...

##view :
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
context['comments'] = Comment.objects.filter(post_id=self.object.id).all()
context['comments_number'] = Comment.objects.filter(post_id=self.object.id).count()
context['form'] = CommentForm()
return context


def post(self, request, pk):
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = Post.objects.get(id=pk)
comment.user = request.user
comment.save()
post = Post.objects.get(pk=pk)
post.comments_nmb+=1
post.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))


##template:
{% extends "blog/base.html" %}
{% block content %}




{{ object.title }}


{{ object.content }}


{{comments_number}} Comments


{% for comment in comments %}






{{ comment.user.username }}


{{comment.text}}

{{ comment.date}}



{% endfor %}


{% endblock content %}

如何在for循环中对评论进行分页?

1 Câu trả lời

几乎完全一样的方式:

from django.core.paginator import Paginator

class PostDetailView(DetailView):
model = Post

def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
page = self.request.GET.get('page')
comments = Paginator(self.object.comment_set.all(), 25)
context['comments'] = comments.get_page(page)
context['comments_number'] = self.object.comment_set.count()
context['form'] = CommentForm()
return context

# ...

我们因此从self.request.GET 参数中获取page 参数,然后我们制作一个Paginator 并相应地对其进行分页。您可能还应该根据某些字段对评论进行排序。现在评论可以以任何顺序出现,因此下一页可以包含出现在上一页的评论,等等。

comments 变量因此是一个分页对象,您可以像在基于函数的 View 中一样呈现它。

请注意,您可以使用 comment_set(或者如果您设置了另一个 related_name,则该名称)来访问与 Post 相关的属性集> 对象。

话虽这么说,也许这更像是一个ListView over the comments,或者一个FormView,因为你包含了一个Form来评论。

关于python - 详细 View 中的分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733232/

27 4 0
Bài viết được đề xuất: Python Keras 预测返回 nan
Bài viết được đề xuất: css - 伪元素 ":after"或 ":before"未在 angular2 应用程序上呈现
Bài viết được đề xuất: javascript - 使用动画单击按钮时需要移动到顶部
Bài viết được đề xuất: python - 相当于 python 中的 java.util.Scanner
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com