我对自己的帖子有评论表格。看起来像这样
view.py
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
#comment.author.photo = object.author.profile.image.url
comment.save()
return redirect('Post-detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
models.py
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=20)
text = models.TextField(max_length=200, verbose_name='内容')
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('text',)
widgets = { #size of textbox
'text': forms.Textarea(attrs={'rows':4}),
}
我应该在哪里添加分页功能以使其起作用?
我对自己的帖子进行了分页,但是帖子使用的是DetailView
类,但我不知道如何使它用于评论function
答案 0 :(得分:1)
基本上,您需要在Post-detail
视图中执行此操作。由于DetailView
不提供分页,因此您需要自己提供它们。您可以覆盖get上下文方法。例如:
from django.core.paginator import Paginator
class PostDetailView(DetailView):
...
def get_context_data(self):
context = super(PostDetailView, self).get_context_data()
_list = Comment.objects.filter(post=self.kwargs.get('pk'))
paginator = Paginator(_list, 25) # Show 25 contacts per page
page = request.GET.get('page')
context['comments'] = paginator.get_page(page)
return context
并在模板中呈现注释,如下所示:
<div class="pagination">
<span class="step-links">
{% if comments.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ comments.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ comments.number }} of {{ comments.paginator.num_pages }}.
</span>
{% if contacts.has_next %}
<a href="?page={{ comments.next_page_number }}">next</a>
<a href="?page={{ comments.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
更多信息也可以在documentation
中找到。
答案 1 :(得分:0)
这是可以做到的。
from rest_framework.pagination import PageNumberPagination
# Create a custom pagination class.
class CommentPagination(PageNumberPagination):
page_size = 1000
page_size_query_param = 'page_size'
max_page_size = 10000
# Define the Pagination class in PostDetailView.
class PostDetailView(DetailView):
pagination_class = CommentPagination
# This is how api can be called.
# something.com/comment/?page=4