Django returns "500 INTERNAL SERVER ERROR" when $ .post is utf-8 string
I ran into the problem that django always returns "500 internal server errors" when I tried to post a utf-8 string (like a chinese string). But I tried to post the ascii string, it looks ok. Also, it works fine on my Archlinux machine, but cannot work on another CentOS server. How can I avoid this problem?
template:
$(".palcesubm").click(function(){
var location = $('#detail_address').val()
$.post('/wechat/locate/select/create/',
{'location':location}, function(){
window.location = "/wechat/locate/baidu/";
})
});
View:
@csrf_exempt
def create_location(request):
if request.method == 'GET':
return render_to_response('create_location.html')
else:
print request.POST.get('location')
request.session['location'] = request.POST.get('location')
return HttpResponse('success')
+3
source to share
2 answers
You are probably getting UnicodeEncodeError because
request.POST.get('location')
returns a unicode object. When you try to print it, Python tries to encode it with the ascii codec and fails because it contains non-ascii characters.
If you really want to print it, use:
print request.POST.get('location').encode('utf-8')
EDIT: More information on encodings in Python: https://docs.python.org/2/howto/unicode.html
+2
source to share