我最近将一些单词(字符串)换成了非英语。现在我在控制台中收到此错误。我使用的是python,django。这是从ajax发生的。我相信python文件我只需要添加" # - - 编码:utf-8 - - "在顶部。我为我的ajax做了同样的事,但它没有做任何事情。 这里; s是完整的错误
UnicodeEncodeError at /notifications/ajax/
'ascii' codec can't encode character u'\ubbbb' in position 98: ordinal not in range(128)
Traceback:
File "/home/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/env/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/notifications/views.py" in get_notifications_ajax
47. notes.append(str(note.get_link))
Exception Type: UnicodeEncodeError at /notifications/ajax/
Exception Value: 'ascii' codec can't encode character u'\ubbbb' in position 98: ordinal not in range(128)
这里;是ajax的功能
@login_required
def get_notifications_ajax(request):
if request.is_ajax() and request.method == "POST":
notifications = Notification.objects.all_for_user(MyProfile.objects.get(user=request.user)).recent()
count = notifications.count()
notes = []
for note in notifications:
notes.append(str(note.get_link))
data = {
"notifications": notes,
"count": count,
}
print data
json_data = json.dumps(data)
print json_data
return HttpResponse(json_data, content_type='application/json')
else:
raise Http404
错误发生在这里;
notes.append(str(note.get_link))
这是我的ajax
<script>
$(document).ready(function(){
$(".notification-toggle").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "{% url 'get_notifications_ajax' %}",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
$("#notification_dropdown").html(' <li role="presentation" class="dropdown-header">view</li>');
var count = data.count
console.log(count)
if (count == 0) {
var url = '{% url "notifications_all" %}'
$("#notification_dropdown").append("<li><a href='" + url+ "'>view all</a></li>")
} else {
$(data.notifications).each(function(){
var link = this;
$("#notification_dropdown").append("<li>" + link + "</li>")
})
}
console.log(data.notifications);
},
error: function(rs, e) {
console.log(rs);
console.log(e);
}
})
})
})
</script>
我切换的是&#34;动词&#34;在这一个: notify.send(MyProfile.objects.get(用户= request.user), 行动= new_comment, 目标= parent_comment, 收件人= parent_comment.user, affected_users = affected_users, 动词=&#39;回复&#39)
我翻译了#39;回复&#39;到韩国,我得到了错误
答案 0 :(得分:2)
在韩文字符上使用str
将在python 2中失败 - 您应该使用.encode()
。因此,将str(note.get_link)
更改为note.get_link.encode('utf-8')
可以使事情顺利进行。
Check out the unicode how to in the docs
>>> x = u'\ubbbb'
>>> x
u'\ubbbb'
>>> type(x)
<type 'unicode'>
>>> str(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\ubbbb' in position 0: ordinal not in range(128)
>>> x.encode('utf-8')
'\xeb\xae\xbb'