gpt4 book ai didi

python - django,使用 ugettext_lazy 时出现 "is not JSON serializable"?

转载 作者:IT老高 更新时间:2023-10-28 20:56:28 24 4
gpt4 key购买 nike

我的 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 = _('这是一条测试消息')

我收到此错误:

 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

为什么?我做错了什么?

最佳答案

您还可以创建自己的 JSON 编码器,它将强制 __proxy__ 为 unicode。

来自 https://docs.djangoproject.com/en/1.8/topics/serialization/

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)

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

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

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

关于python - django,使用 ugettext_lazy 时出现 "is not JSON serializable"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19734724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com