我得到了这个例外,我所理解的是,通过json传递带有对象的字典:
Internal Server Error: /dashboard/ajax/reload_data/
Traceback (most recent call last):
File "/home/micael/Documents/MySite/local/lib/python2.7/site-packages /django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/micael/Documents/MySite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/micael/Documents/MySite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/micael/Documents/djangoDashboard/dashboard/views.py", line 34, in reload_data
data = json.dumps(content)
File "/usr/lib/python2.7/json/__init__.py", line 244, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <QuerySet [{u'nome_cliente': u'ABBBBA'}, {u'nome_cliente': u'MediaPrime'}, {u'nome_cliente': u'ITeCons'}, {u'nome_cliente': u'ABA'}, {u'nome_cliente': u'ABBA'}, {u'nome_cliente': u'SELT'}]> is not JSON serializable
[16/May/2018 17:15:57] "GET /dashboard/ajax/reload_data/ HTTP/1.1" 500 21406ajax视图:
def reload_data(request):
if request.is_ajax():
b = Jobs.objects.order_by('end_time').reverse()[:10]
u = Update.objects.values('nome_cliente').distinct()
content = {"backup_info": b, "update_info": u}
x = Cliente.objects.all()
for x in Cliente.objects.all():
now = time.time()
minTime = now - 86400 #last_28h
n_jobs_last_24h = Jobs.objects.filter(id_cliente_id=x.id_cliente, insert_time__range=(minTime, now)).count()
if n_jobs_last_24h < x.n_jobs:
#faltam jobs
messages.add_message(request, messages.WARNING, 'Cliente %s com menos %s jobs!' % (x.identificador, (x.n_jobs - n_jobs_last_24h)))
data = json.dumps(content)
return HttpResponse(data, content_type='application/json')
else:
raise Http404模板代码:
<div id ="update">
<div id="dash1div">
<a href="">
<strong>Updates</strong>
</a>
</div>
<ul>
{% for update_info in update_info %}
<li>
<a id = "{{update_info.nome_cliente}}" href="/dashboard/ListUpdate/{{update_info.nome_cliente}}/">{{update_info.nome_cliente}}</a>
</li>
{% endfor %}
</ul>
</div>Ajax代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
console.log('am i called');
$.ajax({
url: '/dashboard/ajax/reload_data/',
success: function (data){
response_json = JSON.parse(data)
$('body').html(response_json.html_data);
}
});
},1000)
</script>我找到了一些解决方案,但我无法使它们适应我的代码!你能帮帮我吗?这是在一段时间内刷新div的最佳解决方案吗?
谢谢你的帮助!
发布于 2018-05-16 17:34:06
对于下列本机python类型,支持JSON编码。
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str, unicode | string |
+-------------------+---------------+
| int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+因此,如果您执行json.dumps(1) ->,它将工作,因为这是默认支持的。
现在,您的变量content是一个python字典;它显然是您可以打开的JSON序列化程序;if (这是一个大的if) --字典的所有内容也都是可以序列化的本机类型。
但是,content的内容是Django Queryset,它不是本机的JSON。
但是,可以使用django的序列化类将查询集转换为所有原生python类型,但如果只返回一个查询集,则效果很好。
由于您正在返回一个字典,其值本身就是查询集,因此我建议您查看Django Rest框架或泰斯皮。
如果您想保持简单;这里有一个很好的解决方法,您可以定义一个自定义编码器,它使用Django的Queryset序列化类,以及用于其他数据类型的内置类:Django:将一个包含查询集的字典序列化为JSON
https://stackoverflow.com/questions/50376556
复制相似问题