我写了一个简单的博客,我的问题是如何在帖子的DetailView中使用Django分页对ForeignKey Comments
进行分页。我知道Django提供了注释框架,但是出于学习目的,我想要一个自己的简单注释系统。
我的models.py
:
class Comment(models.Model):
comment_text = models.TextField(blank=True)
comment_author = models.CharField(
max_length=50, help_text="Enter your nickname.")
comment_date = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comment')
Views.py:
class PostDetailView(generic.DetailView):
model = Post
和模板:
{% extends "base_generic.html" %}
{% block title %}
<title>Blog Post</title>
{% endblock %}
{% block content %}
<div>
<h1>{{post.title}}</h1>
<em>{{post.post_date}} by {{post.author}}</em> {% if post.author == user %}<a class="btn btn-dark btn-sm" href="{% url 'edit_post' post.id %}">Edit</a>|<a class="btn btn-dark btn-sm" href="{% url 'delete_post' post.id %}">Delete</a>{%endif%}
{%if post.image %}<div class="post-image"><img src="{{post.image.url}}"></div>{%endif%}
<div class="post-content"><p>{{post.post_text}}</p></div>
<div style="margin-left:20px;margin-top:20px">
<h4>Comments</h4>
{%if post.comment %}
{%for comment in post.comment.all %}
<hr>
<em>Posted by {{comment.comment_author}} on {{comment.comment_date}}</em>
<p>{{comment.comment_text}}</p>
{%endfor%}
{%endif%}
<a href="{%url 'comment_post' post.id%}" class='btn btn-success'>Add a comment</a>
</div>
{% endblock %}
我的分页已经在base_generic.html
中,我所寻找的只是如何将基于类的视图扩展为仅对注释实例进行分页。
答案 0 :(得分:0)
我会稍微扭转一下。您可以将其看作是评论及其相关文章的列表页面,而不是显示Post的详细信息页面然后对评论进行分页。 ListView已经包含分页功能;因此,您要做的就是按帖子过滤评论,并将帖子本身添加到上下文中。所以:
class CommentListView(generic.ListView):
model = Comment
def get_context_data(self, *args, **kwargs):
self.object = Post.objects.get(pk=self.kwargs['pk'] # or whatever your URL is
return super().get_context_data(post=self.object)
def get_queryset(self):
return super().get_queryset().filter(post=self.object)
您的模板变为:
...
<div style="margin-left:20px;margin-top:20px">
<h4>Comments</h4>
{%for comment in object_list %}
<hr>
<em>Posted by {{comment.comment_author}} on {{comment.comment_date}}</em>
<p>{{comment.comment_text}}</p>
{%endfor%}
... pagination links here...