2017-12-02 4 views
0

私は多くのフィールドを持つフォームを持っていますが、選択した国と選択した国の都市を選択する2つの選択肢があります。AJAX、Django、およびHTMLを選択しますか?

私はこれをしたいと思います:最初の選択で国を選択すると、選択した主義のIDでフィルタリングされた2番目の都市の都市を変更したいと思います。ここで

は私のModels.py

class country(models.Model): 
    country_name = models.CharField(max_length=264) 
    def __str__(self): 
     return self.country_name 

class country_cities(models.Model): 
    city_name = models.CharField(max_length=264) 
    country = models.ForeignKey(country) 
    def __str__(self): 
     return self.city_name 

されており、ここに私のHTMLフォームです:

<form method="post"> 
    <input type="text" name="username"> 
    <select name="country" onchange="listCities()"> 
    {% for country in countrylist %} 
     <option value="{{ country.id }}">{{ country.country_name }}</option> 
    {% endor %} 
    </select> 
    <select name="city" id="citylist"> 
    <!--HERE IS WHERE I WANT TO LIST JUST THE CITIES OF THE COUNTRY THAT I SELECTED--> 

    </select> 
</form> 

は、どのように私は私のビューを作成しないと私は私のviews.pyにインポートする必要がどのようなライブラリ?また、私のAJAXライブラリやスクリプトが正しいかどうかはわかりません。

AJAX:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> 
</script> 

SCRIPT:

<script type="text/javascript"> 
    function listCities() 
    { 
    var countryid = $("[name='country']").val(); 
    $('#citylist').html(''); 
    $.ajax({ 
     type: "POST", 
     data: "countryid="+countryid, 
     url: "editprofile/", 
     success: function(result) 
     { 
     var resultObj = JSON.parse(result); 
     var dataHandler = $("#citylist"); 
     $.each(resultObj, function(key, val) 
     { 
      var newRow = $('<option value="'+val.id+'">'); 
      newRow.html(' '+val.city_name +''); 
      dataHandler.append(newRow); 
     }); 

     } 
    }); 
    } 
</script> 
+0

Ajaxコールを行う代わりに、すべての都市をjsonオブジェクトのクライアント側にロードし、プレーンなjavascriptを使用して2番目の選択でオプションを変更することを検討しましたか? – DragonBobZ

+0

これはどのように見えるかについての手伝いhttps://jsfiddle.net/q4np1169/です。 (jqueryを使用し、プレーンなjsは使用しない) – DragonBobZ

答えて

0

私は似たようなのためにgetJSONの代わりPOSTを使用。これは、HTMLからonchangeを取り出し、代わりにselectボックスIDが#countrylistで、changeをjQuery内で使用することを前提としています。これは、選択ボックスからの値を国の検索idとして使用します。

ajax呼び出しにはviewが必要です。 AJAX部分の変数urlはそれに接続します。私はあなただけCityにごcountry_citiesモデルの名前を変更することをお勧めする可能性がある場合、また

#views.py 
#...other imports... 
from django.core import seralizers 

def select_country(request): 
    if request.method == 'GET' and request.is_ajax(): 
    selected_country = request.GET.get('id') 
    json_city = serializers.serialize("json", country_cities.objects.filter(country_id = selected_country)) 
    return HttpResponse(json_city, content_type='application/json') 
    else: 
    return HttpResponse("no-go") 

#YourScript.js 
$(function(){ 
//...your AJAX configurations would go up here, like CSRF stuff... 

$(document).on('change', "#countrylist", function(e) { 
    e.preventDefault(); 
    console.log($(this).val()); 
    var url = http://127.0.0.1:8000/yourURLtoView 
    $.getJSON(url, {id: $(this).val()}, function(j) { 
     var options = '<option value="">---??---</option>'; 
     for (var i = 0; i < j.length; i++) { 
      options += '<option value="' + parseInt(j[i].pk) + '">' + j[i].fields['city_name'] + '</option>'; 
     } 
     console.log(options); //This should show the new listing of filtered options. 
     $("#citylist").html(options); 
     $("#citylist option:first").attr('selected', 'selected'); 
    }); 
    $("#countrylist").attr('selected', 'selected'); 
}); 

}); 

:あなたのviews.pyscript.jsはこのようなものを持つことができます。クラスを適切なエンティティとして、CarまたはPersonまたはComputerのように想像してください。私が自分のファイルの1つからそれを書き写そうとしたときに、これがうまくいくかどうかを教えてください。

関連する問題