Search code examples
ajaxdjangoget

how to fix django error MultiValueDictKeyError


I am new to Django and I am trying to fetch data from the database into a dropdown list where i have 3 chained dropdown list.

When I use request.GET, the system display the below error:

raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'cnt'

traceback

Traceback (most recent call last): File "C:\Users\LTGM~1\Desktop\TEST2F~1\test2\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\LTGM~1\Desktop\TEST2F~1\test2\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\LTGM~1\Desktop\TEST2F~1\test2\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\LT GM\Desktop\test2ForImportExport\test2\testpro\views.py", line 23, in getdetails country_name = request.GET['cnt'] File "C:\Users\LTGM~1\Desktop\TEST2F~1\test2\lib\site-packages\django\utils\datastructures.py", line 79, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'cnt' [21/Feb/2019 09:02:28] "GET /getdetails/ HTTP/1.1" 500 15859

models.py

class country(models.Model):
    name = models.CharField(max_length=100)

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

class city(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(country,on_delete=models.CASCADE)


    def __str__(self):

        return str(self.name)

class road(models.Model):
    Vil = models.CharField(max_length=100)
    city= models.ForeignKey(city,on_delete = models.SET_NULL, null=True)
    country= models.ForeignKey(country,on_delete = models.SET_NULL,null=True)

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

urls.py

from django.contrib import admin
from django.urls import path, include
from.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home2),
    path('getdetails/', getdetails),

home2.html

<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>       

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


        </select>



    </body>
</html>

views.py

from django.shortcuts import render
from django.http import HttpResponse
from testapp.models import *

import json as simplejson



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

def getdetails(request):

    country_name = request.GET['cnt'] # here is the error 
    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.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),content_type='application/json')

What I expect is that once the user select from the first dropdown list the second dropdown will display only the data that belong to the first selection.


Solution

  • Can you change your script as below and see if it works:

    <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:'/getdetails',<--maybe a proper url is required leading to your view
                         data:JSON.stringify(data),
                         dataType: "json",
                         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>');
                            };
    
    
                    });
                });
    
            });
        </script>
    

    Your view:

     def getdetails(request):
    
        if request.method == 'GET' and request.is_ajax():
            country_name = request.GET.get('cnt',None) 
            print ("ajax country_name ", country_name)
            ............
        else:
            #return something
    

    The error may be caused due to the data not being converted into JSON format. Maybe you need to change your view function after this.