Browse By

Add Chain Combo Using Jquery and ajax in Django framework

Hello, friends…

Add Chain Combo Using Jquery and ajax in Django frameworkWe have seen how to Start Django automatically after restarting development system/server in Linux in the previous article. After that, I have started developing the classified website using Django framework. During the development phase, I faced problem regarding the implementation of Chain Combo. After so many trials, I succeeded in implementing Chain Combo using Jquery and ajax.

I thought many developers may have face same issue during developing the site. So I decided to create an article on “how to add Chain Combo using Jquery and ajax in Django framework”. :-)
Are you ready to learn? Let’s start…

Direct Download Full Source Code

Add Chain Combo Using Jquery and ajax in Django framework

  1. Create one virtual environment using “virtualenv <name of virtualenv>”

2. Install Django == 1.9.2, djangorestframework == 3.3.2

3. Create the project in Django, after creating three applications Country, State and City models of all three are like

4.  Create class Country into country/models.py

class Country(models.Model):
    country_name = models.CharField(max_length=100,verbose_name = _('Country Name'))
    
    def __unicode__(self,):
        return str(self.country_name)

5. Create class State into state/models.py

class State(models.Model): 
    country = models.ForeignKey('country.Country')
    state_name = models.CharField(max_length=100,verbose_name = _('State Name'))
    
    
    def __unicode__(self,):
        return str(self.state_name)

6. Create class City into city/models.py

class City(models.Model):
    state = models.ForeignKey('state.State')
    city_name = models.CharField(max_length=100,verbose_name = _('City Name'))
    
    def __unicode__(self,):
        return str(self.city_name)

7.  After define all three models we have to create web services that return data in JSON format for that we used djangorestframework

8. Create one application in Django called api

9. api/serializers.py

class CountrySerializer(serializers.ModelSerializer):

    class Meta:
        model=Country
        fields = '__all__' 
        
class StateSerializer(serializers.ModelSerializer):
    class Meta:
        model=State
        fields = '__all__' 
        
class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model=City
        fields = '__all__'

10. api/views.py

@api_view(['GET'])
@csrf_exempt
def get_country(request):
    countryobj = Country.objects.all()
    country_serializer = CountrySerializer(countryobj, many=True)
    response = Response(country_serializer.data)    
    return Response(response.data,status=status.HTTP_200_OK)

@api_view(['GET'])
@csrf_exempt
def get_state(request, sid):
    stateobj = State.objects.filter(country=sid)
    state_serializer = StateSerializer(stateobj, many=True)
    response = Response(state_serializer.data)
    return Response(response.data,status=status.HTTP_200_OK)

@api_view(['GET'])
@csrf_exempt
def get_city(request, cid):
    cityobj = City.objects.filter(state=cid)
    city_serializer = CitySerializer(cityobj, many=True)
    response = Response(city_serializer.data)
    return Response(response.data,status=status.HTTP_200_OK)

After that, we get all JSON data for country, state and city

11. We get all JSON data and using ajax parse, now place them in select choice using jquery

<script type="text/JavaScript">
    $select = $('#country');
    $.ajax({
      url: '/api/get_country/',
      dataType:'JSON',
      success:function(data){
        $.each(data, function(key, val){
          $select.append('<option value="' + val.id + '">' + val.country_name + '</option>');
        })
      },
    });
      
function getState() {
    $select = $('#state');
    $city = $('#city');
    var c_id = ($("select[name='country'] option:selected").attr('value'));
    c_url = "/api/get_state/"+c_id+"/";
    $.ajax({
      url: c_url,
      dataType:'JSON',
      success:function(data1){
        $select.html('');
        $.each(data1, function(key, val){
          $select.append('<option value="' + val.id + '">' + val.state_name + '</option>');
        })
        getCity();
      },
    });
}

function getCity() {
    $select = $('#city');
    var s_id = ($("select[name='state'] option:selected").attr('value'));
    s_url = "/api/get_city/"+s_id+"/";
    
    $.ajax({
      url: s_url,
      dataType:'JSON',
      success:function(data1){
        $select.html('');
        $.each(data1, function(key, val){
          $select.append('<option value="' + val.id + '">' + val.city_name + '</option>');
        })
      },
    });
}
</script>

Write same functions for state and city field 

12. Open below URL in your browser after run Django server:

  http://127.0.0.1:8000/country/render/

13. Output is:

Add Chain Combo Using Jquery and ajax in Django framework

I hope you like this article. Share your views to to improve content. Please stay tune with us. Happy Coding !!!

Subscribe for more articles!!

Download Full Source Code