jQuery $.post to Django returns "500 Internal Server Error"
I am working on the jQuery tutorial (Link) but have been stuck at the section, "RATE ME: USING AJAX"
jQuery:
$(document).ready(function() {
// generate markup
$("#rating").append("Please rate: ");
for ( var i = 1; i <= 5; i++ )
$("#rating").append("<a href='#'>" + i + "</a> ");
// add markup to container and apply click handlers to anchors
$("#rating a").click(function(e){
// stop normal link click
e.preventDefault();
// send request
$.post("/vote", {rating: $(this).html()}, function(xml) {
// format and output result
$("#rating div").html(
"Thanks for rating, current average: " +
$("average", xml).text() +
", number of votes: " +
$("count", xml).text()
);
});
});
});
urls.py:
urlpatterns = patterns('',
(r'^rating/$', 'ajax_rating.views.rating'),
(r'^vote/$', 'ajax_rating.views.vote'),
)
views.py:
@csrf_exempt
def vote(request):
if request.is_ajax():
rating = request['rating']
f = open('ratings.dat', 'w')
votes = json.load(f)
votes.append(rating)
f.close()
dict = {}
total_rating = sum(votes)
dict['count'] = len(votes)
dict['avg'] = total_rating / dict['count']
return HttpResponse(serializers.serialize('xml', dict), 'application/xml')
else:
return HttpResponse(status=400)
Basically, the html offers the user to make a choice between 1 to 5 (anchors with class=rating). Once a choice is clicked, the #rating div would get refreshed with the calculated result returned from the server.
Problem: I am getting "HTTP 500 Internal Server Error" when I click on a choice. The error happens even before the request hits the view function, vote(request). I have tried to figure out why the error but don't have any clues. I don't thi开发者_开发问答nk it has anything to do with csrf as I am using @csrf_exempt on the view function and have taken out 'django.middleware.csrf.CsrfViewMiddleware' from MIDDLEWARE_CLASSES.
Please help~~ thanks to you experts
I believe the POST should go to the URL /vote/
and not just /vote
.
rating
would not be a valid key on request
. You are probably looking for request.POST['rating']
. Or, to be safe so that you don't throw even more key errors:
rating = request.POST.get('rating', None)
if rating is None:
return HttpResponse(status=400) ## or some error.
精彩评论