как отобразить выбранные параметры из выпадающего списка с помощью Django - PullRequest
0 голосов
/ 27 февраля 2019

У меня есть 3 зависимых выпадающих списков проселочной дороги.где пользователь делает свой выбор, система работает как надо.

мой вопрос:

как отобразить выбранную опцию на странице?

пример:

выбранная страна = ??

выбранный город = ??

выбранная дорога = ??

Я отправляю данные из вида в виде json где он отображается в раскрывающемся списке

Мне также необходимо отправить выбранные данные в виде словаря, чтобы иметь возможность отображать на шаблоне правильный результат, как показано в показанном примере.

home.html

<html>
    <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
        <script>$(document).ready(function(){
             $('select#selectcountries').change(function () {
                 var optionSelected = $(this).find("option:selected");
                 var valueSelected  = optionSelected.val();
                 var country_name   = optionSelected.text();


                 data = {'cnt' : country_name };

                 $.ajax({
                     type:"GET",
                     url:'/getCity',
                     // data:JSON.stringify(data),
                     data:data,
                     success:function(result){
                        console.log(result);
                        $("#selectcities option").remove();
                        for (var i = result.length - 1; i >= 0; i--) {
                            $("#selectcities").append('<option>'+ result[i].name +'</option>');
                        };
                      },
                });
            });

            $('select#selectcities').change(function () {
                 var optionSelected = $(this).find("option:selected");
                 var valueSelected  = optionSelected.val();
                 var city_name   = optionSelected.text();


                 data = {'ct' : city_name };

                 $.ajax({
                     type:"GET",
                     url:'/getRoads',
                     // data:JSON.stringify(data),
                     data:data,
                     success:function(result){
                        console.log(result);
                        $("#selectroads option").remove();
                        for (var i = result.length - 1; i >= 0; i--) {
                            $("#selectroads").append('<option>'+ result[i].name +'</option>');
                        };
                      },
                });
            }); 
        });
        </script>
    </head>

    <body>
        <select name="selectcountries" id="selectcountries">
        {% for item in countries %}
            <option val="{{ item.name }}"> {{ item.name }} </option>    
        {% endfor %}
        </select>   


        <select name ="selectcities" id="selectcities">


        </select>

        <select name ="selectroads" id="selectroads">


        </select>

        <p>the selected country {{ selected_country }}</p>
        <p> the selected city  {{ selected_city }}</p>



    </body>
</html>

views.py

from django.shortcuts import render,redirect, render_to_response
from map.models import *
import json as simplejson
from django.http import HttpResponse,JsonResponse
# Create your views here.


def index(request):

    countries = Country.objects.all()
    print (countries)
    return render(request, 'home.html', {'countries': countries})


def getCity(request):
    if request.method == 'GET' and request.is_ajax():
        country_name = request.GET.get('cnt', None) 
        print ("ajax country_name ", country_name)

        result_set = []
        all_cities = []

        answer = str(country_name[1:-1])

        print('answer = ' ,answer)
        selected_country = Country.objects.get(name=answer)
        print ("selected country name ", selected_country)

        all_cities = selected_country.cities.all()
        print("cities are: " , all_cities)
        for city in all_cities:
            print ("city name", city.name)
            result_set.append({'name': city.name})

        return HttpResponse(simplejson.dumps(result_set),content_type='application/json')
        # return render_to_response(simplejson.dumps(result_set),content_type='application/json', {'selected_country':selected_country})

        # return JsonResponse(result_set,status = 200)

    else:
        return redirect('/')


def getRoads(request):
    if request.method == 'GET' and request.is_ajax():
        city_name = request.GET.get('ct', None) 
        print ("ajax city_name ", city_name)

        result_set = []
        all_roads = []

        # answer = str(city_name[1:-1])
        answer = str(city_name)
        print('answer = ' ,answer)
        selected_city = City.objects.get(name=answer)
        print ("selected city name ", selected_city)

        all_roads = selected_city.roads.all()
        print("roads are: " , all_roads)
        for road in all_roads:
            print ("road name", road.name)
            result_set.append({'name': road.name})

        return HttpResponse(simplejson.dumps(result_set),content_type='application/json')
        # return render_to_response(simplejson.dumps(result_set),content_type='application/json', {'selected_city':selected_city})
        # return JsonResponse(result_set,status = 200)

    else:
        return redirect('/')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...