分页Django评论的最简洁/最简单的方法是使用Django自带的评论系统,然后自定义一个评论模型并设置分页。
首先,你需要在Django应用程序的settings.py文件中添加Django的评论系统。可以通过以下命令添加评论系统:
INSTALLED_APPS = [
# ...
'django.contrib.comments',
'django.contrib.contenttypes',
# ...
]
然后,你需要在Django应用程序的urls.py文件中添加评论系统的URL路由。可以通过以下命令添加URL路由:
from django.urls import path
from . import views
urlpatterns = [
# ...
path('comments/', views.CommentListView.as_view(), name='comments'),
path('comments/<int:pk>/', views.CommentDetailView.as_view(), name='comment-detail'),
path('comments/<int:pk>/vote/', views.vote, name='comment-vote'),
path('comments/new/', views.CommentCreateView.as_view(), name='comment-create'),
path('comments/<int:pk>/edit/', views.CommentUpdateView.as_view(), name='comment-edit'),
path('comments/<int:pk>/delete/', views.CommentDeleteView.as_view(), name='comment-delete'),
]
接下来,你需要在Django应用程序的views.py文件中自定义评论模型并设置分页。可以通过以下命令自定义评论模型并设置分页:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse, JsonResponse
def comments_list(request, content_type_id, object_id, page=1):
content_type = get_object_or_404(ContentType, pk=content_type_id)
object_id = int(object_id)
comments = Comment.objects.filter(content_type=content_type, object_id=object_id).order_by('-created_at')
paginator = Paginator(comments, 10)
try:
comments_list = paginator.page(page)
except PageNotAnInteger:
comments_list = paginator.page(1)
except EmptyPage:
comments_list = paginator.page(paginator.num_pages)
return render(request, 'comments/list.html', {'comments_list': comments_list})
最后,你需要在Django应用程序的templates文件夹中创建一个名为list.html的模板,用于显示评论列表。可以通过以下命令创建模板:
touch templates/comments/list.html
在模板中,你可以使用以下代码来显示评论列表:
{% extends 'base.html' %}
{% block content %}
<h2>评论列表</h2>
<div class="row">
<div class="col-8">
<div class="card">
<div class="card-header">
<h5>所有评论</h5>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>用户</th>
<th>评论内容</th>
<th>评分</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for comment in comments_list %}
<tr>
<td>{{ comment.user }}</td>
<td>{{ comment.content }}</td>
<td>{{ comment.rating }}</td>
<td>{{ comment.created_at }}</td>
<td>
<a href="{% url 'comment-edit' comment.id %}"><i class="fas fa-pencil-alt"></i></a>
<a href="{% url 'comment-delete' comment.id %}"><i class="fas fa-trash-alt"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-4">
<div class="card">
<div class="card-
领取专属 10元无门槛券
手把手带您无忧上云