0

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.

Community
  • 1
  • 1
awwester
  • 9,623
  • 13
  • 45
  • 72
  • Exactly what bit are you having trouble with? JS or Python? – Daniel Roseman Oct 22 '13 at 07:13
  • I'm having trouble with the JS. If I could get the data to return in my view (in this example, through a simple HttpResponse), I would be good to go on the rest. Thanks. – awwester Oct 22 '13 at 14:01
  • looking at the console log, it looks like it is trying to pass the JSON object in the Post, but is getting a 403 permission error. Failed to load resource: the server responded with a status of 403 (FORBIDDEN) With the post, does it need a CSRF token passed along with the JSON request somehow? – awwester Oct 23 '13 at 12:25

3 Answers3

2

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

mohitmayank
  • 631
  • 2
  • 7
  • 20
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Use the standard Python library for deserializing the JSON data, and simply use the Django model API to create and save your object:

import json
import models.Mymodel
data = json.loads(request.POST['testJSON'])
for elem in data:
    m = MyModel(elem)
    m.save()

For the JS side, look for jQuery.param to submit JSON requests.

Zack4
  • 153
  • 1
  • 10
0

It was a problem with the csrf, and I was getting a 403 error when passing the JSON object.

I included the code from documentation in the main js file, and I needed to include {% csrf_token %} on the origin html page.

awwester
  • 9,623
  • 13
  • 45
  • 72