使用ugettext_lazy时,django“不是JSON可序列化的”?

时间:2013-11-01 20:17:35

标签: python django json

我在views.py

中有这个
response_dict = {
    'status': status,
    'message': message
}
return HttpResponse(simplejson.dumps(response_dict),
                    mimetype='application/javascript')

因为我开始使用这个导入:

from django.utils.translation import ugettext_lazy as _

在这一行:

message = _('This is a test message')

我收到此错误:

 File "/home/chris/work/project/prokject/main/views.py", line 830, in fooFunc
    return HttpResponse(simplejson.dumps(response_dict),

  File "/usr/local/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)

  File "/usr/local/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)

  File "/usr/local/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)

  File "/usr/local/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")

TypeError: <django.utils.functional.__proxy__ object at 0x7f42d581b590> is not JSON serializable

为什么呢?我做错了什么?

2 个答案:

答案 0 :(得分:46)

您还可以创建自己的JSON编码器,强制from django.utils.functional import Promise from django.utils.encoding import force_text from django.core.serializers.json import DjangoJSONEncoder class LazyEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Promise): return force_text(obj) return super(LazyEncoder, self).default(obj) 进行unicode。

来自here

response_dict = {
    'status': status,
    'message': _('Your message')
}

return HttpResponse(json.dumps(response_dict, cls=LazyEncoder),
                    mimetype='application/javascript')

所以现在你的代码看起来像:

ListViewOnPreviewMouseLeftButtonDown

答案 1 :(得分:20)

它还不是一个字符串,并且Python的JSON编码器不知道ugettext_lazy,所以你必须强制它成为类似

的字符串
response_dict = {
    'status': status,
    'message': unicode(message)
}