gpt4 book ai didi

python - 如何通过这种方式使用分页不起作用

转载 作者:行者123 更新时间:2023-12-04 10:03:40 24 4
gpt4 key购买 nike

views.py paginate_by 不起作用,并且“if”语句在“get_queryset”中不起作用有什么办法可以解决这个问题

class PostListView(ListView):
model = Post
template_name = 'all_users/public/main.html'
context_object_name = 'posts'
paginate_by = 3

def get(self, request, **kwargs):
if request.user.is_public:
post = Post.objects.filter(patient=self.request.user).order_by('-date_posted')
context = {
'posts': post,
}
return render(request, self.template_name, context)

else:
query = self.request.session['query']
post = Post.objects.filter(patient=User.objects.get(username=query)).order_by('-date_posted')
context = {
'posts': post,
}
return render(request, self.template_name, context)

最佳答案

Django 将对源自 get_queryset 的查询集进行分页.因此,您可以使用以下方法实现 View :

from django.contrib.auth.mixins import LoginRequiredMixin

class PostListView(LoginRequiredMixin, ListView):
template_name = 'all_users/doctor/main.html'
model = Post
context_object_name = 'posts'
paginate_by = 3

def get_queryset(self, *args, **kwargs):
super().get_queryset(*args, **kwargs).filter(
author=self.request.user
).order_by('-date_posted')

它将添加 Page反对名称为 page_obj 的上下文.所以你可以迭代它:
{% for post in page_obj %}
{{ post }}
{% endfor %}

编辑 : 或有条件:
from django.contrib.auth.mixins import LoginRequiredMixin

class PostListView(ListView):
template_name = 'all_users/doctor/main.html'
model = Post
context_object_name = 'posts'
paginate_by = 3

def get_queryset(self, *args, **kwargs):
qs = super().get_queryset(*args, **kwargs)
if self.request.user.is_public:
qs = qs.filter(
author=self.request.user
)
else:
qs = qs.filter(
patient__username=self.request.session['query']
)
return qs.order_by('-date_posted')

Note: You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc].

关于python - 如何通过这种方式使用分页不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61695742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com