Django dependent select

well , i coded a whole project just for you , hope this could help 🙂 :
in this project i we have countries which have many cities
as shown in pictures, each time you select a country , only related cities shown in next combo box 🙂

iran's cities

USA's cities

ok , no let’s see the code
(full project source code is on my github : https://github.com/nodet07/Django-Related-DropDowns)
models.py :
just 2 simple models , a country which can have many cities !

 from django.db import models
    class City(models.Model):
        name = models.CharField(max_length=50)
        country = models.ForeignKey("Country")
        def __unicode__(self):
            return u'%s' % (self.name)

    class Country(models.Model):
        name = models.CharField(max_length=50)
        def __unicode__(self):
            return u'%s' % (self.name)

views.py:

from django.shortcuts import render
from map.models import *
from django.utils import simplejson
from django.http import HttpResponse

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

def getdetails(request):
    #country_name = request.POST['country_name']
    country_name = request.GET['cnt']
    print "ajax country_name ", country_name

    result_set = []
    all_cities = []
    answer = str(country_name[1:-1])
    selected_country = Country.objects.get(name=answer)
    print "selected country name ", selected_country
    all_cities = selected_country.city_set.all()
    for city in all_cities:
        print "city name", city.name
        result_set.append({'name': city.name})
    return HttpResponse(simplejson.dumps(result_set), mimetype="application/json",     content_type="application/json")

index.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('/getdetails',data,function(result){

                            console.log(result);
                            $("#selectcities option").remove();
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectcities").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>

    </body>
</html>

Leave a Comment