Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.post to Django returns "500 Internal Server Error"

Tags:

jquery

django

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 think 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

like image 860
tamakisquare Avatar asked May 09 '11 19:05

tamakisquare


1 Answers

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

like image 165
Satyajit Avatar answered Oct 05 '22 03:10

Satyajit