JQuery $ .post for Django returns "500 Internal Server Error"

I am working on a jQuery tutorial ( Link ) but am stuck in the "RATE ME: USING AJAX" section

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, html prompts the user to choose between 1 and 5 (anchors with class = rating). After clicking on the selection, the #rating div will be updated with the calculated result returned from the server.

Problem: I get the message "Internal HTTP 500 server error" when I click on a selection. The error occurs even before the request hits the view function by voting (request). I tried to find out why the error, but has no clues. I don't think this has anything to do with csrf as I use @csrf_exempt for the view function and pulled "django.middleware.csrf.CsrfViewMiddleware" from MIDDLEWARE_CLASSES.

Please help ~~ thanks to you experts

+6
source share
2 answers

rating will 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. 
+6
source

I believe that POST should go to the URL /vote/ , not just /vote .

+22
source

Source: https://habr.com/ru/post/887654/


All Articles