2017-12-06 1 views
1

ページ設定とフィルタ形式のページを作成しています(2 GETリクエスト)。 URLにページ分割とフィルタ結果の両方が含まれている場合は、/questions/?page=2&all_questions=onのようにうまくいきます。フィルタ結果がある場合は、/questions/?all_questions=onのようにも動作します。Django - 別のGETリクエストでページ区切り。ページ番号だけでは動作しません。

ページ分割ページの結果しかない場合は、/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}) 
+1

あなたは試してみました: question_list = Question.objects.all()ORDER_BY( ' - DATE_CREATEDを') ページネータ=ページネータ(question_list、15。 ) questions = paginator.page(page) –

答えて

4

問題は最初であり、最後ではありません。あなたが書く時:

if not form.is_bound: 
    question_list = Question.objects.all().order_by('-date_created') 

この条件は、request.GETが空の場合にのみ満たされます。 is_boundメソッドは、辞書のキーがフォームフィールド(docs)でないかどうかにかかわらず、データを与えるとTrueを返します。説明した場合、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') 
+0

ありがとうございます。それはそれだった。期限が切れると賞金を授与します – Valachio

関連する問題