我对基于类的视图相当新,我遇到了问题。
我实现了get_queryset以返回我的所有用户(用于测试)并返回它们并且分页工作正常(在get_queryset之外,我确实有" paginate_by"字段集)。
然后,用户可以通过POST搜索某些特定用户,并且post方法的结尾是:
return render(request, self.template_name, {'objects': some_users})
它工作正常,但分页失去了。我做错了什么?
答案 0 :(得分:1)
分页在paginate_queryset
中完成,由get_context_data
调用,由post
调用(默认为子get
),所以你可以像这样(假设您有一个基于帖子数据过滤的过滤方法:
def post(self, request, *args, **kwargs):
self.queryset = self.filter(self.get_queryset())
return super(MyView, self).get(request, *args, **kwargs)
父帖会调用get_queryset
,会返回已过滤的self.queryset
,并会在调用get_context_data
不在第一个get
上显示查询集,
def get(self, request, *args, **kwargs):
return self.self.response_class(
request=self.request,
template=self.get_template_names())
分页模板链接应始终发布到视图而不是默认的get,因此请在上下文中保存搜索输入并更改分页的模板,
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['search_value'] = self.request.POST.get('search_name', None)
return context
,
<form action="?page={{ page_obj.previous_page_number }}" method="post">
{% csrf_token %}
<input type="hidden" value="{{ search_value }}" name="search_name">
<button type="submit">«</button>
</form>
以及下一个链接:
<form action="?page={{ page_obj.next_page_number }}" method="post">
{% csrf_token %}
<input type="hidden" value="{{ search_value }}" name="search_name">
<button type="submit">»</button>
</form>
答案 1 :(得分:0)
我已经使用会话来完成这些工作。 现在,我可以使用POST进行搜索了,分页效果很好
def MySearch(request):
if request.method == 'POST':
search_text = request.POST.get('search_string')
request.session['search'] = search_text
query_set = MyModel.objects.filter(myattribute__icontains=search_text)
paginator = Paginator(search, 1)
page = request.GET.get('page')
search = paginator.get_page(page)
return render(request, 'myapp/mytemplate.html', {'page_obj': search})
if request.method == 'GET':
if 'search' in request.session:
query_set = MyModel.objects.filter(myattribute__icontains=search_text)
paginator = Paginator(search, 1)
page = request.GET.get('page')
search = paginator.get_page(page)
return render(request, 'myapp/mytemplate.html', {'page_obj': search})
else:
return render(request, 'myapp/mytemplate.html')