JSON object sent from Javascript to Django Views is empty









up vote
0
down vote

favorite












I'm trying to send some data from Javascript to Django through ajax.
Here is my JS code:



 var json_name = 'name': 123
$.ajax(
method: 'POST',
url: 'my url',
contentType: "application/json",
headers:
'Content-Type':'application/json',
'X-CSRFToken': " csrf_token "
,

data: JSON.stringify(json_name),
success: function (data)
//this gets called when server returns an OK response
alert("it worked!");
,
error: function (data)
alert("it didnt work");

);


Here is my Views.py:



def myview(request):
if request.is_ajax():
request_data = request.body
# data = json.loads(request.body)
print(request_data)
# print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')


I get the output as b''



When I try to include these lines:



data = json.loads(request.body)
print(data)


I get this error:



TypeError: the JSON object must be str, not 'bytes'


I took some reference from here



Can someone help me with this? If you need any additional information to solve this, I'll be happy to share.










share|improve this question





















  • and what does json_name contain in your JavaScript? Have you checked it's populated as you expect before sending the request?
    – ADyson
    Nov 10 at 12:22










  • Yes, I put console.log(json_name) before sending the request and it is outputted as: name: 123
    – Vinay Varma
    Nov 10 at 12:47










  • How are you triggering that Ajax post? Is it on a button click? If so did you call preventDefault()? Show rest of the script and the html?
    – Daniel Roseman
    Nov 10 at 13:02










  • do you try data = json.loads(request.body.decode('utf-8') print(data)
    – Bast
    Nov 10 at 13:18










  • Possible duplicate of Get request body as string in Django
    – jacobian
    Nov 10 at 13:43














up vote
0
down vote

favorite












I'm trying to send some data from Javascript to Django through ajax.
Here is my JS code:



 var json_name = 'name': 123
$.ajax(
method: 'POST',
url: 'my url',
contentType: "application/json",
headers:
'Content-Type':'application/json',
'X-CSRFToken': " csrf_token "
,

data: JSON.stringify(json_name),
success: function (data)
//this gets called when server returns an OK response
alert("it worked!");
,
error: function (data)
alert("it didnt work");

);


Here is my Views.py:



def myview(request):
if request.is_ajax():
request_data = request.body
# data = json.loads(request.body)
print(request_data)
# print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')


I get the output as b''



When I try to include these lines:



data = json.loads(request.body)
print(data)


I get this error:



TypeError: the JSON object must be str, not 'bytes'


I took some reference from here



Can someone help me with this? If you need any additional information to solve this, I'll be happy to share.










share|improve this question





















  • and what does json_name contain in your JavaScript? Have you checked it's populated as you expect before sending the request?
    – ADyson
    Nov 10 at 12:22










  • Yes, I put console.log(json_name) before sending the request and it is outputted as: name: 123
    – Vinay Varma
    Nov 10 at 12:47










  • How are you triggering that Ajax post? Is it on a button click? If so did you call preventDefault()? Show rest of the script and the html?
    – Daniel Roseman
    Nov 10 at 13:02










  • do you try data = json.loads(request.body.decode('utf-8') print(data)
    – Bast
    Nov 10 at 13:18










  • Possible duplicate of Get request body as string in Django
    – jacobian
    Nov 10 at 13:43












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm trying to send some data from Javascript to Django through ajax.
Here is my JS code:



 var json_name = 'name': 123
$.ajax(
method: 'POST',
url: 'my url',
contentType: "application/json",
headers:
'Content-Type':'application/json',
'X-CSRFToken': " csrf_token "
,

data: JSON.stringify(json_name),
success: function (data)
//this gets called when server returns an OK response
alert("it worked!");
,
error: function (data)
alert("it didnt work");

);


Here is my Views.py:



def myview(request):
if request.is_ajax():
request_data = request.body
# data = json.loads(request.body)
print(request_data)
# print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')


I get the output as b''



When I try to include these lines:



data = json.loads(request.body)
print(data)


I get this error:



TypeError: the JSON object must be str, not 'bytes'


I took some reference from here



Can someone help me with this? If you need any additional information to solve this, I'll be happy to share.










share|improve this question













I'm trying to send some data from Javascript to Django through ajax.
Here is my JS code:



 var json_name = 'name': 123
$.ajax(
method: 'POST',
url: 'my url',
contentType: "application/json",
headers:
'Content-Type':'application/json',
'X-CSRFToken': " csrf_token "
,

data: JSON.stringify(json_name),
success: function (data)
//this gets called when server returns an OK response
alert("it worked!");
,
error: function (data)
alert("it didnt work");

);


Here is my Views.py:



def myview(request):
if request.is_ajax():
request_data = request.body
# data = json.loads(request.body)
print(request_data)
# print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')


I get the output as b''



When I try to include these lines:



data = json.loads(request.body)
print(data)


I get this error:



TypeError: the JSON object must be str, not 'bytes'


I took some reference from here



Can someone help me with this? If you need any additional information to solve this, I'll be happy to share.







javascript json ajax django






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 12:13









Vinay Varma

35




35











  • and what does json_name contain in your JavaScript? Have you checked it's populated as you expect before sending the request?
    – ADyson
    Nov 10 at 12:22










  • Yes, I put console.log(json_name) before sending the request and it is outputted as: name: 123
    – Vinay Varma
    Nov 10 at 12:47










  • How are you triggering that Ajax post? Is it on a button click? If so did you call preventDefault()? Show rest of the script and the html?
    – Daniel Roseman
    Nov 10 at 13:02










  • do you try data = json.loads(request.body.decode('utf-8') print(data)
    – Bast
    Nov 10 at 13:18










  • Possible duplicate of Get request body as string in Django
    – jacobian
    Nov 10 at 13:43
















  • and what does json_name contain in your JavaScript? Have you checked it's populated as you expect before sending the request?
    – ADyson
    Nov 10 at 12:22










  • Yes, I put console.log(json_name) before sending the request and it is outputted as: name: 123
    – Vinay Varma
    Nov 10 at 12:47










  • How are you triggering that Ajax post? Is it on a button click? If so did you call preventDefault()? Show rest of the script and the html?
    – Daniel Roseman
    Nov 10 at 13:02










  • do you try data = json.loads(request.body.decode('utf-8') print(data)
    – Bast
    Nov 10 at 13:18










  • Possible duplicate of Get request body as string in Django
    – jacobian
    Nov 10 at 13:43















and what does json_name contain in your JavaScript? Have you checked it's populated as you expect before sending the request?
– ADyson
Nov 10 at 12:22




and what does json_name contain in your JavaScript? Have you checked it's populated as you expect before sending the request?
– ADyson
Nov 10 at 12:22












Yes, I put console.log(json_name) before sending the request and it is outputted as: name: 123
– Vinay Varma
Nov 10 at 12:47




Yes, I put console.log(json_name) before sending the request and it is outputted as: name: 123
– Vinay Varma
Nov 10 at 12:47












How are you triggering that Ajax post? Is it on a button click? If so did you call preventDefault()? Show rest of the script and the html?
– Daniel Roseman
Nov 10 at 13:02




How are you triggering that Ajax post? Is it on a button click? If so did you call preventDefault()? Show rest of the script and the html?
– Daniel Roseman
Nov 10 at 13:02












do you try data = json.loads(request.body.decode('utf-8') print(data)
– Bast
Nov 10 at 13:18




do you try data = json.loads(request.body.decode('utf-8') print(data)
– Bast
Nov 10 at 13:18












Possible duplicate of Get request body as string in Django
– jacobian
Nov 10 at 13:43




Possible duplicate of Get request body as string in Django
– jacobian
Nov 10 at 13:43












2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










After losing half the hair on my head, I solved it in the following way:



views.py:



from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def myview(request):
if request.is_ajax():
if request.method == 'POST':
data = request.POST.get('senddata')
print(data)
return render(request, 'candidate/view.html')
else:
return render(request, 'candidate/view.html')


my JS code:



 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

$.ajax(
type: 'POST',
url: 'my url',
// contentType: "application/json",
// headers:
// 'Content-Type':'application/json',
// 'X-CSRFToken': " csrf_token "
// ,
dataType: "json",
data:
senddata: JSON.stringify(json_name),
,

// data: json_name,

success: function (data)
//this gets called when server returns an OK response
alert("it worked!");
,
error: function (data)
alert("it didnt work");

);


When I run it, it shows it didnt work but I can see the output in my terminal i.e The data was passed.



I tried including the csrf token in the ajax request but it failed. Therefore I used csrf_exempt in my views.



This might be a dirty way of doing things, but it works for now. If anyone has a neat and better answer please post it here!!






share|improve this answer



























    up vote
    -1
    down vote













    I've written a basic testcase on Django 1.11 with Python 3.6 and Python 2.7.



    I have been using the following template file to test:



    <button>Send data</button>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
    $('button').on('click', function(event)
    var data = name: 123 ;
    $.ajax(
    method: 'POST',
    url: '',
    contentType: 'application/json',
    headers:
    'X-CSRFToken': ' csrf_token ',
    ,
    data: JSON.stringify(data),
    success: function()
    console.log('Success!');
    ,
    error: function()
    console.log('Error...');
    ,
    );
    );
    </script>


    And the following route, which delivers the template file and prints any AJAX data:



    from django.http import response
    from django.shortcuts import render
    import json

    def index(request):
    if request.is_ajax():
    request_body = request.body
    data = json.loads(request_body)
    print(data)
    return render(request, 'stackoverflowhelp/index.html')


    I've not been able to reproduce the issue.



    However, having done more research I found that the json.loads method in Python 3.6 supports bytes objects, while the documentation for Python 2.7 json.loads suggests it only supports string types. While the error you've posted reflects this, I've attempted to make this generate the same error as you're seeing but have had no success.



    As you can see, I've not had to whitelist the method from CSRF protection. Based purely on the error you've provided, calling decode on request.body may work:



    def index(request):
    if request.is_ajax():
    request_body = request.body.decode("utf-8")
    data = json.loads(request_body)
    print(data)
    return render(request, 'stackoverflowhelp/index.html')





    share|improve this answer






















    • method: 'POST', url: 'my url', contentType: "application/json", headers: 'Content-Type':'application/json', 'X-CSRFToken': " csrf_token " , datatype: "json", processData: false, data: json_name, Thanks for the information, it gave me some conceptual understanding. However, I still get the same output as b' '.
      – Vinay Varma
      Nov 10 at 19:07











    • I can't see how this answer is at all relevant. OP is already converting the data to a JSON string. And dataType is for the datat that is returned by the server, not what is sent.
      – Daniel Roseman
      Nov 10 at 19:08










    • You're right, sorry. I've seen this kind of issue before and it's usually been because JQuery encodes the data as a query-string. I've since written a testcase and it appears to be sending the data correctly. I'm going to modify my answer with the solution.
      – Marcus Harrison
      yesterday










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238830%2fjson-object-sent-from-javascript-to-django-views-is-empty%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    After losing half the hair on my head, I solved it in the following way:



    views.py:



    from django.views.decorators.csrf import csrf_exempt

    @csrf_exempt
    def myview(request):
    if request.is_ajax():
    if request.method == 'POST':
    data = request.POST.get('senddata')
    print(data)
    return render(request, 'candidate/view.html')
    else:
    return render(request, 'candidate/view.html')


    my JS code:



     <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

    $.ajax(
    type: 'POST',
    url: 'my url',
    // contentType: "application/json",
    // headers:
    // 'Content-Type':'application/json',
    // 'X-CSRFToken': " csrf_token "
    // ,
    dataType: "json",
    data:
    senddata: JSON.stringify(json_name),
    ,

    // data: json_name,

    success: function (data)
    //this gets called when server returns an OK response
    alert("it worked!");
    ,
    error: function (data)
    alert("it didnt work");

    );


    When I run it, it shows it didnt work but I can see the output in my terminal i.e The data was passed.



    I tried including the csrf token in the ajax request but it failed. Therefore I used csrf_exempt in my views.



    This might be a dirty way of doing things, but it works for now. If anyone has a neat and better answer please post it here!!






    share|improve this answer
























      up vote
      0
      down vote



      accepted










      After losing half the hair on my head, I solved it in the following way:



      views.py:



      from django.views.decorators.csrf import csrf_exempt

      @csrf_exempt
      def myview(request):
      if request.is_ajax():
      if request.method == 'POST':
      data = request.POST.get('senddata')
      print(data)
      return render(request, 'candidate/view.html')
      else:
      return render(request, 'candidate/view.html')


      my JS code:



       <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

      $.ajax(
      type: 'POST',
      url: 'my url',
      // contentType: "application/json",
      // headers:
      // 'Content-Type':'application/json',
      // 'X-CSRFToken': " csrf_token "
      // ,
      dataType: "json",
      data:
      senddata: JSON.stringify(json_name),
      ,

      // data: json_name,

      success: function (data)
      //this gets called when server returns an OK response
      alert("it worked!");
      ,
      error: function (data)
      alert("it didnt work");

      );


      When I run it, it shows it didnt work but I can see the output in my terminal i.e The data was passed.



      I tried including the csrf token in the ajax request but it failed. Therefore I used csrf_exempt in my views.



      This might be a dirty way of doing things, but it works for now. If anyone has a neat and better answer please post it here!!






      share|improve this answer






















        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        After losing half the hair on my head, I solved it in the following way:



        views.py:



        from django.views.decorators.csrf import csrf_exempt

        @csrf_exempt
        def myview(request):
        if request.is_ajax():
        if request.method == 'POST':
        data = request.POST.get('senddata')
        print(data)
        return render(request, 'candidate/view.html')
        else:
        return render(request, 'candidate/view.html')


        my JS code:



         <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

        $.ajax(
        type: 'POST',
        url: 'my url',
        // contentType: "application/json",
        // headers:
        // 'Content-Type':'application/json',
        // 'X-CSRFToken': " csrf_token "
        // ,
        dataType: "json",
        data:
        senddata: JSON.stringify(json_name),
        ,

        // data: json_name,

        success: function (data)
        //this gets called when server returns an OK response
        alert("it worked!");
        ,
        error: function (data)
        alert("it didnt work");

        );


        When I run it, it shows it didnt work but I can see the output in my terminal i.e The data was passed.



        I tried including the csrf token in the ajax request but it failed. Therefore I used csrf_exempt in my views.



        This might be a dirty way of doing things, but it works for now. If anyone has a neat and better answer please post it here!!






        share|improve this answer












        After losing half the hair on my head, I solved it in the following way:



        views.py:



        from django.views.decorators.csrf import csrf_exempt

        @csrf_exempt
        def myview(request):
        if request.is_ajax():
        if request.method == 'POST':
        data = request.POST.get('senddata')
        print(data)
        return render(request, 'candidate/view.html')
        else:
        return render(request, 'candidate/view.html')


        my JS code:



         <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

        $.ajax(
        type: 'POST',
        url: 'my url',
        // contentType: "application/json",
        // headers:
        // 'Content-Type':'application/json',
        // 'X-CSRFToken': " csrf_token "
        // ,
        dataType: "json",
        data:
        senddata: JSON.stringify(json_name),
        ,

        // data: json_name,

        success: function (data)
        //this gets called when server returns an OK response
        alert("it worked!");
        ,
        error: function (data)
        alert("it didnt work");

        );


        When I run it, it shows it didnt work but I can see the output in my terminal i.e The data was passed.



        I tried including the csrf token in the ajax request but it failed. Therefore I used csrf_exempt in my views.



        This might be a dirty way of doing things, but it works for now. If anyone has a neat and better answer please post it here!!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 8:33









        Vinay Varma

        35




        35






















            up vote
            -1
            down vote













            I've written a basic testcase on Django 1.11 with Python 3.6 and Python 2.7.



            I have been using the following template file to test:



            <button>Send data</button>
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script>
            $('button').on('click', function(event)
            var data = name: 123 ;
            $.ajax(
            method: 'POST',
            url: '',
            contentType: 'application/json',
            headers:
            'X-CSRFToken': ' csrf_token ',
            ,
            data: JSON.stringify(data),
            success: function()
            console.log('Success!');
            ,
            error: function()
            console.log('Error...');
            ,
            );
            );
            </script>


            And the following route, which delivers the template file and prints any AJAX data:



            from django.http import response
            from django.shortcuts import render
            import json

            def index(request):
            if request.is_ajax():
            request_body = request.body
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')


            I've not been able to reproduce the issue.



            However, having done more research I found that the json.loads method in Python 3.6 supports bytes objects, while the documentation for Python 2.7 json.loads suggests it only supports string types. While the error you've posted reflects this, I've attempted to make this generate the same error as you're seeing but have had no success.



            As you can see, I've not had to whitelist the method from CSRF protection. Based purely on the error you've provided, calling decode on request.body may work:



            def index(request):
            if request.is_ajax():
            request_body = request.body.decode("utf-8")
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')





            share|improve this answer






















            • method: 'POST', url: 'my url', contentType: "application/json", headers: 'Content-Type':'application/json', 'X-CSRFToken': " csrf_token " , datatype: "json", processData: false, data: json_name, Thanks for the information, it gave me some conceptual understanding. However, I still get the same output as b' '.
              – Vinay Varma
              Nov 10 at 19:07











            • I can't see how this answer is at all relevant. OP is already converting the data to a JSON string. And dataType is for the datat that is returned by the server, not what is sent.
              – Daniel Roseman
              Nov 10 at 19:08










            • You're right, sorry. I've seen this kind of issue before and it's usually been because JQuery encodes the data as a query-string. I've since written a testcase and it appears to be sending the data correctly. I'm going to modify my answer with the solution.
              – Marcus Harrison
              yesterday














            up vote
            -1
            down vote













            I've written a basic testcase on Django 1.11 with Python 3.6 and Python 2.7.



            I have been using the following template file to test:



            <button>Send data</button>
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script>
            $('button').on('click', function(event)
            var data = name: 123 ;
            $.ajax(
            method: 'POST',
            url: '',
            contentType: 'application/json',
            headers:
            'X-CSRFToken': ' csrf_token ',
            ,
            data: JSON.stringify(data),
            success: function()
            console.log('Success!');
            ,
            error: function()
            console.log('Error...');
            ,
            );
            );
            </script>


            And the following route, which delivers the template file and prints any AJAX data:



            from django.http import response
            from django.shortcuts import render
            import json

            def index(request):
            if request.is_ajax():
            request_body = request.body
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')


            I've not been able to reproduce the issue.



            However, having done more research I found that the json.loads method in Python 3.6 supports bytes objects, while the documentation for Python 2.7 json.loads suggests it only supports string types. While the error you've posted reflects this, I've attempted to make this generate the same error as you're seeing but have had no success.



            As you can see, I've not had to whitelist the method from CSRF protection. Based purely on the error you've provided, calling decode on request.body may work:



            def index(request):
            if request.is_ajax():
            request_body = request.body.decode("utf-8")
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')





            share|improve this answer






















            • method: 'POST', url: 'my url', contentType: "application/json", headers: 'Content-Type':'application/json', 'X-CSRFToken': " csrf_token " , datatype: "json", processData: false, data: json_name, Thanks for the information, it gave me some conceptual understanding. However, I still get the same output as b' '.
              – Vinay Varma
              Nov 10 at 19:07











            • I can't see how this answer is at all relevant. OP is already converting the data to a JSON string. And dataType is for the datat that is returned by the server, not what is sent.
              – Daniel Roseman
              Nov 10 at 19:08










            • You're right, sorry. I've seen this kind of issue before and it's usually been because JQuery encodes the data as a query-string. I've since written a testcase and it appears to be sending the data correctly. I'm going to modify my answer with the solution.
              – Marcus Harrison
              yesterday












            up vote
            -1
            down vote










            up vote
            -1
            down vote









            I've written a basic testcase on Django 1.11 with Python 3.6 and Python 2.7.



            I have been using the following template file to test:



            <button>Send data</button>
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script>
            $('button').on('click', function(event)
            var data = name: 123 ;
            $.ajax(
            method: 'POST',
            url: '',
            contentType: 'application/json',
            headers:
            'X-CSRFToken': ' csrf_token ',
            ,
            data: JSON.stringify(data),
            success: function()
            console.log('Success!');
            ,
            error: function()
            console.log('Error...');
            ,
            );
            );
            </script>


            And the following route, which delivers the template file and prints any AJAX data:



            from django.http import response
            from django.shortcuts import render
            import json

            def index(request):
            if request.is_ajax():
            request_body = request.body
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')


            I've not been able to reproduce the issue.



            However, having done more research I found that the json.loads method in Python 3.6 supports bytes objects, while the documentation for Python 2.7 json.loads suggests it only supports string types. While the error you've posted reflects this, I've attempted to make this generate the same error as you're seeing but have had no success.



            As you can see, I've not had to whitelist the method from CSRF protection. Based purely on the error you've provided, calling decode on request.body may work:



            def index(request):
            if request.is_ajax():
            request_body = request.body.decode("utf-8")
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')





            share|improve this answer














            I've written a basic testcase on Django 1.11 with Python 3.6 and Python 2.7.



            I have been using the following template file to test:



            <button>Send data</button>
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script>
            $('button').on('click', function(event)
            var data = name: 123 ;
            $.ajax(
            method: 'POST',
            url: '',
            contentType: 'application/json',
            headers:
            'X-CSRFToken': ' csrf_token ',
            ,
            data: JSON.stringify(data),
            success: function()
            console.log('Success!');
            ,
            error: function()
            console.log('Error...');
            ,
            );
            );
            </script>


            And the following route, which delivers the template file and prints any AJAX data:



            from django.http import response
            from django.shortcuts import render
            import json

            def index(request):
            if request.is_ajax():
            request_body = request.body
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')


            I've not been able to reproduce the issue.



            However, having done more research I found that the json.loads method in Python 3.6 supports bytes objects, while the documentation for Python 2.7 json.loads suggests it only supports string types. While the error you've posted reflects this, I've attempted to make this generate the same error as you're seeing but have had no success.



            As you can see, I've not had to whitelist the method from CSRF protection. Based purely on the error you've provided, calling decode on request.body may work:



            def index(request):
            if request.is_ajax():
            request_body = request.body.decode("utf-8")
            data = json.loads(request_body)
            print(data)
            return render(request, 'stackoverflowhelp/index.html')






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited yesterday

























            answered Nov 10 at 13:49









            Marcus Harrison

            314212




            314212











            • method: 'POST', url: 'my url', contentType: "application/json", headers: 'Content-Type':'application/json', 'X-CSRFToken': " csrf_token " , datatype: "json", processData: false, data: json_name, Thanks for the information, it gave me some conceptual understanding. However, I still get the same output as b' '.
              – Vinay Varma
              Nov 10 at 19:07











            • I can't see how this answer is at all relevant. OP is already converting the data to a JSON string. And dataType is for the datat that is returned by the server, not what is sent.
              – Daniel Roseman
              Nov 10 at 19:08










            • You're right, sorry. I've seen this kind of issue before and it's usually been because JQuery encodes the data as a query-string. I've since written a testcase and it appears to be sending the data correctly. I'm going to modify my answer with the solution.
              – Marcus Harrison
              yesterday
















            • method: 'POST', url: 'my url', contentType: "application/json", headers: 'Content-Type':'application/json', 'X-CSRFToken': " csrf_token " , datatype: "json", processData: false, data: json_name, Thanks for the information, it gave me some conceptual understanding. However, I still get the same output as b' '.
              – Vinay Varma
              Nov 10 at 19:07











            • I can't see how this answer is at all relevant. OP is already converting the data to a JSON string. And dataType is for the datat that is returned by the server, not what is sent.
              – Daniel Roseman
              Nov 10 at 19:08










            • You're right, sorry. I've seen this kind of issue before and it's usually been because JQuery encodes the data as a query-string. I've since written a testcase and it appears to be sending the data correctly. I'm going to modify my answer with the solution.
              – Marcus Harrison
              yesterday















            method: 'POST', url: 'my url', contentType: "application/json", headers: 'Content-Type':'application/json', 'X-CSRFToken': " csrf_token " , datatype: "json", processData: false, data: json_name, Thanks for the information, it gave me some conceptual understanding. However, I still get the same output as b' '.
            – Vinay Varma
            Nov 10 at 19:07





            method: 'POST', url: 'my url', contentType: "application/json", headers: 'Content-Type':'application/json', 'X-CSRFToken': " csrf_token " , datatype: "json", processData: false, data: json_name, Thanks for the information, it gave me some conceptual understanding. However, I still get the same output as b' '.
            – Vinay Varma
            Nov 10 at 19:07













            I can't see how this answer is at all relevant. OP is already converting the data to a JSON string. And dataType is for the datat that is returned by the server, not what is sent.
            – Daniel Roseman
            Nov 10 at 19:08




            I can't see how this answer is at all relevant. OP is already converting the data to a JSON string. And dataType is for the datat that is returned by the server, not what is sent.
            – Daniel Roseman
            Nov 10 at 19:08












            You're right, sorry. I've seen this kind of issue before and it's usually been because JQuery encodes the data as a query-string. I've since written a testcase and it appears to be sending the data correctly. I'm going to modify my answer with the solution.
            – Marcus Harrison
            yesterday




            You're right, sorry. I've seen this kind of issue before and it's usually been because JQuery encodes the data as a query-string. I've since written a testcase and it appears to be sending the data correctly. I'm going to modify my answer with the solution.
            – Marcus Harrison
            yesterday

















             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238830%2fjson-object-sent-from-javascript-to-django-views-is-empty%23new-answer', 'question_page');

            );

            Post as a guest














































































            這個網誌中的熱門文章

            Barbados

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3