【发布时间】:2018-10-29 19:39:36
【问题描述】:
我写了一个简单的博客,我的问题是如何使用 Django 分页来分页 ForeignKey Comments 在帖子的 DetailView 中。我知道 Django 提供 cmets 框架,但出于学习目的,我自己的简单评论系统正是我想要的。
我的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 中,我正在寻找的只是如何将基于类的视图扩展为仅对 cmets 实例进行分页。
【问题讨论】:
标签: django pagination