简体   繁体   中英

Posting JSON to Django views with AJAX

I am trying to post a JSON object from my client side Javascript to my Django View.

I receive a "500 (Internal Server Error)" When attempting to Post. Does this have to do with the CSRF token? And how can I get around this?

My AJAX

  $.ajax({
      type: 'POST',
      dataType: 'json',
      url: '/demo/saved/',
      data: {'data': JSON.stringify(finalSelection)},
      success: function() {
         console.log("Success")
      }
    });

views.py

def show(request):
    data = json.loads(request.POST.get('data', ''))
    context = {
        'data': data
    }
    return render(request, 'bill/saved.html', context )

urls.py

urlpatterns = [
    path('bill/', views.bill_view, name = 'bill-view'),
    path('saved/', views.show, name = 'selected-view'),
]

Appreciate any help!

Assuming its really the CSRF problem you mentioned, since you didn't post the 500 error output, you can simply add the csrf token to your data that is sent in POST request:

$.ajax({
...
    data: {
        'data': JSON.stringify(finalSelection),
        'csrfmiddlewaretoken': '{{ csrf_token }}'
    },
...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM