0

i have 3 dependent dropdownlists country city road.

where country is pre-populated from the database and based on the selection of the first the second will display the related cities.

the problem is that when user select a country the city is populated but the road display undefined

yet in the cmd it display the correct answer.

template displayed as html page

cmd display the correct results

models.py

from django.db import models


class Road(models.Model):
    name = models.CharField(max_length=50)
    city = models.ForeignKey("City", on_delete=models.CASCADE, related_name='roads')

    def __str__(self):
        return str(self.name)


class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey("Country", on_delete=models.CASCADE, related_name='cities')

    def __str__(self):
        return str(self.name)


class Country(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return str(self.name)

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].Vil +'</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>
    </body>
</html>

views.py

from django.shortcuts import render, redirect
from map.models import *
import json as simplejson
from django.http import HttpResponse


# 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.POST['country_name']
        # country_name = request.GET['cnt']
        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 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 JsonResponse(result_set,status = 200)

    else:
        return redirect('/')

1 Answer 1

1

Typo

$("#selectroads").append('<option>'+ result[i].name +'</option>');
Sign up to request clarification or add additional context in comments.

2 Comments

I was already writing this same answer, seems OP problem should be fixed :)!
a silly mistake i did not replaced result[i].Vil with result[i].name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.