我正在使用分页和过滤器表单构建一个页面(2个GET请求)。如果网址包含分页和过滤结果,例如/questions/?page=2&all_questions=on
,则可以正常使用。如果它只有过滤结果,例如/questions/?all_questions=on
。
但是,如果它只有/questions/?page=1
这样的分页页面结果,则不会显示任何结果。
所以我想我需要对视图做一些事情,这样如果URL中只有一个页码,就会给出一个默认的过滤器。我知道我可能需要在分页的Try and Except部分添加一些内容,但我对我需要编写的实际代码感到难过。
def questions_index(request):
user = request.user
form = QuestionFilterForm(request.GET or None)
question_list = []
if not form.is_bound:
question_list = Question.objects.all().order_by('-date_created')
if form.is_valid():
if form.cleaned_data['all_questions'] | (form.cleaned_data['general_questions'] & form.cleaned_data['location_all_gta']) == True:
question_list = Question.objects.all().order_by('-date_created')
elif form.cleaned_data['location_all_gta'] == True:
question_list += Question.objects.filter(question_type=1).order_by('-date_created')
else:
if form.cleaned_data['general_questions'] == True:
question_list += Question.objects.filter(question_type=2).order_by('-date_created')
if form.cleaned_data['location_toronto'] == True:
question_list += Question.objects.filter(location='1').order_by('-date_created')
paginator = Paginator(question_list, 15)
# Pagination
page = request.GET.get('page')
try:
questions = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
questions = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
questions = paginator.page(paginator.num_pages)
### I need to write something here...
except (url has no filter result)
give default filter
return render(request, 'questions_index.html', {'questions': questions, 'user': user, 'form': form})
答案 0 :(得分:4)
你的问题是在开头,而不是在最后。当你写:
if not form.is_bound:
question_list = Question.objects.all().order_by('-date_created')
只有request.GET
为空时才会满足此条件。如果您向其提供任何数据,is_bound
方法将返回True
,无论字典的键是否不是表单字段(phd)。在您描述的情况下,request.GET
仅包含page
密钥。
一种可能的解决方案是将此部分重写为:
if not form.is_bound or (len(request.GET) == 1 and 'page' in request.GET):
question_list = Question.objects.all().order_by('-date_created')