我有一個問題,使用Django模板發送json數據到前面(html)。傳遞數據json使用Django模板到前面(html)
這是Python代碼:
@api_view(['GET'])
@renderer_classes((JSONRenderer,))
def tasks_list_all(request):
i = inspect()
tasks_dic=i.registered_tasks()
for cle in tasks_dic.keys():
key=cle
tasks_old_v=tasks_dic.get(key)
tasks_new_v=[]
for tasks in tasks_old_v:
new_tasks=tasks.replace('infra_mngt.tasks.','')
tasks_new_v.append(new_tasks)
add_new=tasks_new_v[-1].replace('provisionning.celery.','')
tasks_new_v[-1]=add_new
tasks_new_v_new=json.dumps(tasks_new_v)
print "json.dumps(tasks_new_v)",tasks_new_v_new
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'), context={'list':tasks_new_v})
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v})
return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v_new})
這是前(tasks_all.html)的代碼:
<h1>Dynamic list tasks</h1>
{% for list in tasks_new_v_new %}
{{ list }}
{% endfor %}
但執行後,我沒有得到的任何元素列表,我需要,只是顯示這個HTML代碼:
<h1>Dynamic list tasks</h1>
對於初學者來說,在你的模板中使用的關鍵是'list'而不是'tasks_new_v_new'。如果你想用它作爲你的密鑰,把'{'list':tasks_new_v_new}'改成'{'tasks_new_v_new':tasks_new_v_new}'' –