8

これに対する解決策を長い間探しましたが、まだ見つかりません。テンプレートに大きなフォームがあり、実際には多数のモデル フォームで構成されています。その大きなフォームの 1 つのフィールドはフォームの一部ではありませんが、views.py の「Institutions」というテーブルから入力された単一の動的ドロップダウン メニューです。Institutions.objects.all()

ここでは、views.py の一部を示します。

def submission_form(request):

    institutions = Institution.objects.all()

    if request.method == 'POST':
        abstractform = AbstractForm(request.POST)
        authorform = AuthorForm(request.POST)

        # Here I want code: if selected institution is this, then do that

        if abstractform.is_valid() and authorform.is_valid()
            new_abstract = abstractform.save()
            new_author = authorform.save()


     else:  
         return render(request, 'records/submission_form.html', {'abstractform': abstractform, 'authorform': authorform, 'institutions':institutions })

これは私のテンプレートのドロップダウンです:

 <select id="ddlInstititions">
    <option value="%">---------</option>
    {% for entry in institutions %} 
     <option value="{{ entry.id }}">{{ entry.name }}</option>
    {% endfor %}
</select>

私の質問は: 選択した entry.name をビューに渡して、そこで使用できるようにすることは可能ですか? そうでない場合、代わりに何をすることをお勧めしますか?

どんな助けでも大歓迎です!

4

2 に答える 2

5

これには jQuery の $.ajax() を使用できます。

#ddlInstititionsJavaScript では、イベント ハンドラーを次のようにバインドできます。

$("#ddlInstitions").on("change", function(){
  var selectedValue = $(this).text();

  $.ajax({
    url : "insititionsSelectHandler/",
    type : "GET",
    data : {"name" : selectedValue},
    dataType : "json",
    success : function(){

    }
  });
});

これにより、ドロップダウンで選択イベントを作成すると、このイベント ハンドラーが起動されます。この URL を `urls.py' のように定義する必要があります。

(r'^/institionsSelectHandler/$', views.insititionsSelectHandler),

そして、次のようなビューメソッド内で値を取得できます

def insititionsSelectHandler(request):
   key = request.GET["name"]
   ...
   ...
   ...
   #and return your results as a HttpResponse object that contains a dict
   return HttpResponse(simplejson.dumps({"success" : "true", "message" : ... }, mimetype = "application/json")
于 2013-11-08T16:28:38.867 に答える