May Y
May Y

Reputation: 179

MultiValueDictKeyError when getting data submitted in form with Ajax in Django

I am learning Django web development by doing. I just learned how to POST data in form via AJAX. Now I have problem getting the data results back.

Below works well for the POST function

def cat_select(request):
    cat_selected=[]
    if request.method=='POST': #raise MultiValueDictKeyError when GET in the browser due to vertical having multiple values
        cat_name=['l2','l3']
        cat_selected=[request.POST[x].split(',') for x in cat_name]
        print(cat_selected)
    else:
        cat_name=['l2','l3']
        cat_selected=[request.GET[x].split(',') for x in cat_name]
        cat_selected=get_result(["US"],cat_selected)
        print(cat_selected)
    return JsonResponse({'cat':cat_selected},safe=False)
<form id="cat_select">{% csrf_token %} 
<input class="site" name="site" type="text">
<input class="l2" name="l2" id="l2" type="text" style="width:30%">
<input class="l3" name="l3" id="l3" type="text" style="width:50%">
<br>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="cat_submit">Submit</button>
</form>
<script type="text/javascript">
$(document).on('submit','#cat_select',function(e){
    e.preventDefault();
    $.ajax({
        type:'POST',
        url:'/cat_select',
        data:{
            l2:$('#l2').val(),
            l3:$('#l3').val(),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function(){
            alert ("selected!")
        }
    });
});
</script>

I tried adding below within $(document).on('submit','#cat_select',function(e){ ,but the console Printed Error

    $.ajax({
                method:'GET',
                url:'/cat_select',
                success:function(data){
                    console.log(data);
                },
                error:function(data){
                    console.log('Error!');
                }
            });
Internal Server Error: /cat_select
Traceback (most recent call last):
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
    list_ = super().__getitem__(key)
KeyError: 'l2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Desktop\searchsite2\esearch\views.py", line 83, in cat_select
    cat_selected=[request.GET[x].split(',') for x in cat_name]
  File "C:\Users\Desktop\searchsite2\esearch\views.py", line 83, in <listcomp>
    cat_selected=[request.GET[x].split(',') for x in cat_name]
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'l2'

I am still not quite sure what caused the MultiValueDictKeyError after reading other posts. I selected two values but this was intended to be multi-select.

How can I get rid of this error? Thanks.

Upvotes: 0

Views: 481

Answers (1)

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

In the GET ajax request, you are not passing 'l2' and 'l3', but your view:

else:
    cat_name=['l2','l3']
    cat_selected=[request.GET[x].split(',') for x in cat_name]

Tries to access both of them, and hence the error.

Pass both of them in the GET ajax request and the error will go away.

Upvotes: 1

Related Questions