简体   繁体   中英

Ajax post 500 internal error in django

in html

<div class="reply-writer" >
    <input type="reply" data-id="{{res.id}}" name="comment" class="form-control reply-input">
</div>

in jquery

$(document).on( "keypress", "input.reply-input",function(e) {
if (e.which == 13) {

    var id =$(this).data("id");
    var cmt = $(this).val();

    var url="http://xxx/comment";
    var data = {
        'res_id': id,
        'comment': cmt,
    };

     $.ajax({
             type: "POST",
             url: url,
             data: data,
             async:false
          }).done(function( items ) {
            alert("done");
          }
        );
    }
});

in views.py

def comment(request):
print request
print "comment" + str(request.POST)

response_data = None
try:
    res_id = request.POST.get(u'res_id', 0)
    comment = request.POST.get(u'comment', None)
    super = request.POST.get(u'super', 0)

    comment = comment.encode('utf-8')

    if res_id !=0 or comment:
        res = Restaurant.objects.filter(id=res_id)[0]
        cmt = Comment(user=request.user, comment=comment, super=super, restaurant=res)
        cmt.save()

        current_cmt = Comment.objects.filter(id=cmt.pk)
        response_data = current_cmt
    else:
        response_data = {}

except Exception as e:
    logging.exception(e)
    raise Http404

print "response_data:"+str(response_data)
return HttpResponse(json.dumps(response_data), content_type="application/json")

in console log

comment<QueryDict: {u'comment': [u'kljlk'], u'res_id': [u'4']}>
response_data:[<Comment: 34.kljlk[2014-03-27 06:58:39+00:00]>]
[27/Mar/2014 15:58:39] "POST /withgirl/comment HTTP/1.1" 500 10046

success to save comment data to db table. why generate 500 server internal error?

I reckon the error is happened when you are returning HttpResponse. I'm using django 1.6 and you can compare to my code below

return HttpResponse(
    json.dumps(result, default=date_handler, sort_keys=True),
    "application/json"
)

def date_handler(obj):
    return obj.isoformat() if hasattr(obj, 'isoformat') else obj

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM