[英]Cant use JsonResponse in Django
I have a bunch of values which I would like to send from views.py
function to my template in Django. 我有一堆值,我想将它们从
views.py
函数发送到Django中的模板。 I saw some topics that the best way is by json
format. 我看到一些主题,最好的方法是使用
json
格式。 So I did so. 所以我照做了。 But because my values are not
ascii
I'm using a upgraded version which worked in normal Http response
but don't work in JSON response
. 但是因为我的值不是
ascii
所以我使用的升级版本在正常的Http response
起作用,但在JSON response
不起作用。
Here is my code 这是我的代码
base = {weather_main_key : weather_main_values, wind_speed_key : wind_speed_value + "m", wind_deg_key : wind_deg_value, base_temp_key : base_temp_value + " ℃", base_press_key : base_press_value + " mbar", base_hum_key : base_hum_value + " % " }
base = json.dumps(base, ensure_ascii=False).encode('utf8')
return JsonResponse(json.dumps(base))
So I had an error msg 所以我有一个错误味精
In order to allow non-dict objects to be serialized set the safe parameter to False.
So I did as it told me 所以我照了
JsonResponse(json.dumps(base, safe=False, ensure_ascii=False).encode('utf8'))
And now the error is 现在的错误是
__init__() got an unexpected keyword argument 'safe'
And I can't move... 而且我不能动...
Whoah, triple encoding. 哇, 三重编码。 Why are you doing that?
你为什么要这么做?
You serialize to json. 您序列化为json。 Then, inside the call to JsonResponse, you serialize to json again.
然后,在对JsonResponse的调用内,您再次序列化为json。 But JsonResponse itself does serialization, so you've serialized three times.
但是JsonResponse本身会进行序列化,因此您已经进行了三次序列化。
Stop that; 别搞了; just pass the dict to JsonResponse.
只需将字典传递给JsonResponse。
base = {weather_main_key : weather_main_values, wind_speed_key : wind_speed_value + "m", wind_deg_key : wind_deg_value, base_temp_key : base_temp_value + " ℃", base_press_key : base_press_value + " mbar", base_hum_key : base_hum_value + " % " }
return JsonResponse(base)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.