質問

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?

役に立ちましたか?

解決 2

Got it - There were 2 problems.

First, in the JS, I noticed there were 2 POSTs being performed. I actually didn't need to write any of the JS, the JRating was performing the POST on its own, and sending it to a variable I set in the settings of the plug-in.

The other problem (the more important one) was in the views.py. I was expecting a variable called 'rating', because that is what I was setting in my JS. In reality, I needed to grab each variable separately, and one of the POST calls wasn't even using the rating variable.

def setrating(request):
    if request.is_ajax():
        if request.method == 'POST':
            rating = json.loads(request.POST['rate'])
            id = json.loads(request.POST['idBox'])
    return HttpResponse("the rating for " + str(id) + " is " + str(rating))

他のヒント

I can suggest several things that can at least help us figure out what the problem is:

  1. set DEBUG = True in your settings so you can get the whole traceback in the result and not just the 500.

  2. Post us the answer you get in the view: print request['POST']

  3. use a ModelForm based on your model and use Django built-in form validation to help you handle the data.

Hope it helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top