如何修复Django错误MultiValueDictKeyError

时间:2019-02-21 07:12:41

标签: ajax django get

我是Django的新手,我正尝试从数据库中获取数据到一个下拉列表,其中有3个链接的下拉列表。

当我使用request.GET时,系统显示以下错误:

  

提高MultiValueDictKeyError(key)   django.utils.datastructures.MultiValueDictKeyError:'cnt'

回溯

  

回溯(最近通话最近):文件   “ C:\ Users \ LTGM〜1 \ Desktop \ TEST2F〜1 \ test2 \ lib \ site-packages \ django \ core \ handlers \ exception.py”,   第34行,在内部       response = get_response(request)文件“ C:\ Users \ LTGM〜1 \ Desktop \ TEST2F〜1 \ test2 \ lib \ site-packages \ django \ core \ handlers \ base.py”,   _get_response中的第126行       响应= self.process_exception_by_middleware(e,request)文件“ C:\ Users \ LTGM〜1 \ Desktop \ TEST2F〜1 \ test2 \ lib \ site-packages \ django \ core \ handlers \ base.py”,   _get_response中的第124行       响应= wraped_callback(request,* callback_args,** callback_kwargs)文件“ C:\ Users \ LT GM \ Desktop \ test2ForImportExport \ test2 \ testpro \ views.py”,第23行,在   细节       country_name = request.GET ['cnt']文件“ C:\ Users \ LTGM〜1 \ Desktop \ TEST2F〜1 \ test2 \ lib \ site-packages \ django \ utils \ datastructures.py”,   第79行,在 getitem       引发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')

我期望的是,一旦用户从第一个下拉列表中进行选择,第二个下拉列表将仅显示属于第一个选择的数据。

2 个答案:

答案 0 :(得分:0)

您可以按以下方式更改脚本并查看其是否有效:

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

您的视图:

 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

该错误可能是由于数据未转换为JSON格式引起的。也许之后您需要更改视图功能。

答案 1 :(得分:0)

似乎是因为cnt数据中不存在GET。更改

 country_name = request.GET['cnt'] 

   country_name = request.GET.get('cnt', None) 

如果您获得None作为country_name,请添加其他检查以作为响应。