I'm setting up a rating system and am struggling to utilize JSON data into my Django view. The end goal will be to save a rating into my BlogSiteRating model:
#models.py
class BlogSiteReview(models.Model):
blog_site = models.ForeignKey(BlogSite)
review_rating = models.IntegerField()
However, I'm not quite to that point yet. I was having 403 errors, but those have been resolved by using the csrf token correctly in the POST. Now I am getting a 500 error passed back from the server, which can be seen in the chrome console.
EDIT: Found the error finally. There are 2 POSTs being performed. Both give a MultiValueDictKeyError error
The first says: Key 'rating' not found in "< QueryDict: {u'rating[rating]': [u'10'], u'rating[csrfmiddlewaretoken]': [u'0468d70cfb6fc425a530d434f5a4c30a'], u'rating[rateid]': [u'7']}>
The second says: "Key 'rating' not found in "< QueryDict: {u'action': [u'rating'], u'rate': [u'10'], u'idBox': [u'7']}>"
Here is the JSON I am passing to my view.
//JSON object being passed into views.py
$(".rating").jRating({
onSuccess : function(element,rate){
var rating = [
{ "id":element.id.replace('rating', ''), "rating":rate}
];
rating["csrfmiddlewaretoken"] = $('input[name=csrfmiddlewaretoken]').val();
alert("Passed id:" + element.id.replace('rating', '') + " and rating:" + rate);
//send post data to django view
$.post('/blogsearch/setrating/', {"rating":rating}, function(msg)
{
if(msg.error == "yes")
{console.log('Error Found: '+ msg.errorMsg);}
}, 'json');
},
onError : function(){
alert('Error : please retry again later, the server did not accept your submission.');
}
});
And finally, here is what I have in my views.py:
#views.py
from django.http import HttpResponse
from django.utils import simplejson
def setrating(request):
if request.is_ajax():
if request.method == 'POST':
simplejson.loads(request.POST['rating'])
#data = 1 #Note: when I uncomment this line, and
#comment the above line, I don't get a 500 error
return HttpResponse("success")
Also, I know I am not attempting to save anything in my model in this example. If I can get the JSON data in my view, I should be able to save it from there without problems. But, if you would like you could help with that code in the answer.
I've been looking at posts for a few days now, and some of the ones that have led me down this path are:
internal server eroor 500 django when using simplejson.loads(request.raw_post_data)
Getting internal server error when trying to handle json in django
I have also tried with importing json instead of simplejson, and I get the same result.
I have played around with using request.raw_post_data as well, but I get the server error with that method. From what I've read it looks like request.POST['rating'] is the right thing to use?