awwester awwester - 27 days ago 8
jQuery Question

JSON data with Django

I'm setting up a rating system using the JRating plug-in for JQuery. I have all the front-end stuff working correctly, and am struggling to store the data in my database.

Through what I have researched, it seems the best way to approach storing the data with this jquery plugin using Django is to post a JSON object. Unfortunately, (and fortunately!) I am a complete newbie with JSON.

The post I found with the most relevant information can be found here: Creating a JSON response using Django and Python

For simplicity sake, I'll show a generic, hard-coded JSON object that I am trying to pass to a django view to store in my database. I currently have this object working and am able to reference it on the page.

<!-- jquery in template -->
var testJSON = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];

$.post('/blogsearch/setrating/', {"testJSON":testJSON}, function(msg)
{
if(msg.error == "yes"){console.log('Error Found: '+ msg.errorMsg);}
});


And then, in my Django view, for this question I will just do something simple. If I could get the data to return in my view, I would be good to go on the rest.

#views.py
def setrating(request):
response_data = {}
return HttpResponse(json.dumps(response_data), content_type="application/json")


I am open to any suggestions, including totally reworking how I'm passing the JSON data to be used in my django view.

Answer

See the documentation on how to include a CSRF token with the Ajax request.