【问题标题】:How to paginate ForeignKey instances in DetailView如何在 DetailView 中对 ForeignKey 实例进行分页
【发布时间】: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 中,我正在寻找的只是如何将基于类的视图扩展为仅对 cme​​ts 实例进行分页。

【问题讨论】:

    标签: django pagination


    【解决方案1】:

    我会稍微改变一下。您可以将其视为 cmets 及其相关帖子的列表页面,而不是显示 Post 的详细信息页面然后对 cme​​ts 进行分页。 ListView 已经包含分页功能;因此,您需要做的就是按帖子过滤 cmets 并将帖子本身添加到上下文中。所以:

    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...
    

    【讨论】:

    • 谢谢你解决了我的问题! def get_context_data(self, pk): self.object = Post.objects.get(pk=self.pk) return super().get_context_data(post=self.object) 这和 kwargs 有什么不同?
    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2013-09-12
    • 2015-02-01
    • 2010-09-30
    • 2012-10-13
    • 2020-05-15
    • 1970-01-01
    相关资源
    最近更新 更多