django 如何为detail_view的注解分页?

ahy6op9u  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(110)

我正在写一个简单的博客,我需要为每个帖子分页评论,但我不知道如何做到这一点。谢谢帮助!有我的模型:

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    short_description = models.CharField(max_length=230, default='Post')
    text = models.TextField()
    is_published = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    username = models.CharField(max_length=35)
    comment = models.CharField(max_length=120)
    is_published = models.BooleanField(default=False)

    def __str__(self):
        return self.comment

以下是我的看法:

class PostDetail(generic.DetailView):
    template_name = 'user/post.html'
    model = Post

def comment_view(request, pk):
    form = CommentCreateForm()
    if request.method == 'POST':
        form = CommentCreateForm(request.POST)
        if form.is_valid():
            username = request.user
            comment = form.cleaned_data['comment']
            Comment.objects.create(username=username, comment=comment, post_id=pk)
            return redirect('PostDetail', pk)
    return render(request, 'user/comment_view.html', {'form': form})

这是我的模板:

{ object.title }}
    {% if object.author.id  %}
    <a href="{% url 'public_profile' object.author.id %}">{{ object.author }}</a>
    {% endif %}
<p>{{ object.text }}</p>
    <h4>Comments</h4>
{% for comment in object.comment_set.all %}
    {{ comment.username }}
    <p>{{ comment }}</p>
{% endfor %}
<p><a href="{% url 'comment_view' object.id %}">Leave comment</a></p>

注解分页是真实的的吗?
我应该如何在detail_view中对注解分页?

ni65a41a

ni65a41a1#

分页就像对数据进行切片,所以你能做的就是过滤所有的数据,然后对其进行切片。

products= Products.obejcts.all()
    page_no=1 #take it from frontend
    page_size = 10 #add how much data you want to show in one page.
    offset = (page_no - 1) * page_size
    products = products[offset:offset + page_size] #slicing of data-> [10:10+10] so it give 10 data list for page_no =1 
    base_url = request.build_absolute_uri()
    next_, prev_ = get_next_prev_url(
        base_url,
        page_no,
        page_size
    )

用于获取下一个前一个url的函数

from urllib import parse as url_parse
   def replace_query_param(url, key, val):
    """
    Given a URL and a key/val pair, set or replace an item in the query
    parameters of the URL, and return the new URL.
    """
    result = url_parse.urlparse(url)
    query_dict = url_parse.parse_qs(result.query, keep_blank_values=True)
    query_dict[key] = [val]
    query = url_parse.urlencode(sorted(list(query_dict.items())), doseq=True)
    return url_parse.urlunsplit((result.scheme, result.netloc, result.path, query, result.fragment))

  


     def get_next_prev_url(url, page_no, result_count, page_len):
            page_param = 'page_no'
            max_page_no = int(result_count / page_len) + int(result_count % page_len != 0)
            next_link = prev_link = None
            if max_page_no > page_no:
                next_link = replace_query_param(url, page_param, page_no + 1)
            if page_no > 1:
                prev_link = replace_query_param(url, page_param, page_no - 1)
            return next_link, prev_link

相关问题