1

私はDjangoで次のことを行う方法に手を包もうとしています:

次のような検索パラメーターを使用してGETリクエストを受け入れるビューがあるとします。

def search(request, id):
    another_model = get_object_or_404(models.AnotherModel, id=id)
    if request.method == 'GET' and 'submit' in request.GET:
        result = {}

        # Expensive db operation to filter based on search query
        # Populates result

        return render(request, "result.html", {
            'result': result,
            'form': forms.ConfirmationForm(another_model=another_model)})

    form = forms.SearchForm(None, another_model=another_model)

    return render(request, "search.html", {'form': form})

検索クエリを受信すると、GETパラメータに基づいて高価なデータベース操作を実行します。結果とフォームは、レンダリングのためにテンプレートに渡されます。

テンプレートでは、フォームアクションが別のビューに投稿するように設定されています。

def confirm(request, id):
    another_model = get_object_or_404(models.AnotherModel, id=id)
    form = forms. ConfirmationForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('done', id)    

    # How to:
    # return render(request, "result.html", {
    #    'result': result,
    #    'form': forms.ConfirmationForm(another_model=another_model)})

これまでのところ、confirm()は、フォームが有効な場合にのみ機能します。私が苦労しているのは、フォームが失敗した場合に、confirm()内の前の検索クエリに基づいて応答を「再作成」する方法です。どういうわけかsearch()からの結果をキャッシュして、confirm()で高価な操作を再度実行する必要がないようにする必要がありますか?それとも、コードを再構築するだけの問題ですか?

(うまくいけば、問題の説明はあまり混乱していません!)

4

1 に答える 1

3

それを行うには3つの方法があります

  1. 結果をキャッシュする
  2. 結果をユーザーのセッションに保存します
  3. 非表示フィールドまたは読み取り専用フィールドを使用して、関連情報をフォームに含めます。
于 2012-11-28T20:55:52.490 に答える