1
我想從視圖查詢集傳遞給javascript函數throught模板:如何將查詢集從Django傳遞給javascript函數?
我view.py
:
def myview(request):
lista=Mymodel.objects.filter(tipo=mytipo)
context_dict['lista']=lista
return render(request, 'mytemplate.html', context_dict)
我template.html
:
<script>
<!--
window.onpageshow = function() {
myfunction('{{lista}}');
};
-->
</script>
我javascript.js
:
function myfunction(lista) {
for (i=0; i<lista.length; i++) {
console.log(lista[i].name)
}
}
問題是lista
成爲一個字符串。我試着用JSONEncoder,但我不知道如何使用。我想避免JsonResponse,因爲我想爲我的模板使用該視圖(如果可能的話)。
編輯:
有在回答提出瞭解決的一個問題:在this link提出
TypeError: Python object is not JSON serializable
和解決方案不工作或者(找不到_meta
屬性被稱爲model_to_dict
)。
JSON.parse不工作
SyntaxError: missing) after argument list
,問題似乎是一個路徑和其他之間:
myfunction(JSON.parse('['/mypath/myimage.png', '/otherpath/otherimage.png', 'etc... ']'));
而且在模板中必須添加|safe
。
Luckly我需要字符串列表,以便:
我view.py
:
def myview(request):
lista=Mymodel.objects.filter(tipo=mytipo)
lista_formatted=[]
for elem in lista:
lista_formatted.append('/media/'+str(elem.myfield))
lista_formatted=json.dumps(lista_formatted)
context_dict['lista']=lista_formatted
return render(request, 'mytemplate.html', context_dict)
我template.html
:
<script>
<!--
window.onpageshow = function() {
myfunction({{lista|safe}});
};
-->
</script>
或者,您可以按照@mkaran的建議來做。 'JSON.parse'將字符串放入函數中,'myfunction(JSON.parse('{{lista}}'));'那 – kennasoft
它工作..關於。看我的編輯 – fabio