3 回答

TA貢獻(xiàn)1783條經(jīng)驗 獲得超4個贊
我試過一個例子。其中 是從 python 腳本發(fā)送變量并在 JavaScript 中訪問其值
1) 在 views.py
from django.shortcuts import render
def home_view(request):
var_name = 'hello'
return render(request, 'home.html', {'var_name':var_name})
2) 在 html 文件中(首頁.html)
<html>
<h1>Home Page</h1>
<input type="button" value="Submit" onclick="fun()">
<script>
function fun(){
console.log('hello world '+ '{{var_name}}' );
}
var temp = '{{var_name}}';
console.log(temp + 20);
</script>
</html>
如果我點擊提交按鈕( 你好世界你好 ) 打印在控制臺。
我存儲了var_name的溫度值,可以進(jìn)一步使用。

TA貢獻(xiàn)1155條經(jīng)驗 獲得超0個贊
從您的示例中,看起來您希望以編程方式訪問Javascript中的Django模型的屬性。
主要結(jié)論是,您首先需要在Javascript中公開要訪問的數(shù)據(jù)結(jié)構(gòu)(即模型)。
下面是您可以嘗試的簡單、經(jīng)過編輯的概念驗證。
import json
def my_view(request):
obj = MyModel.objects.get(1)
obj_dict = {
"foo": obj.foo,
"bar": obj.bar,
}
return render(request, 'my_view.html', context={'obj_json': json.dumps(obj_dict)} )
<script>
var obj = {{obj_json}};
var field = 'foo';
console.log(obj[field]);
查看轉(zhuǎn)換 Django 模型對象到字典,所有字段都完好無損,了解將 Django 模型序列化為字典的選項。

TA貢獻(xiàn)2003條經(jīng)驗 獲得超2個贊
好吧,最后我找到了兩個暴露的問題的解決方案。
首先,我聲明的腳本函數(shù)不起作用,因為它似乎有一個屬性叫做autocomplete(參見autocomplete HTML屬性),所以,你不能用這個名字聲明一個JavaScript函數(shù),我的失敗。
Uncaught TypeError: autocomplete is not a function
最后,我發(fā)現(xiàn)的簡單解決方案是將一組字典傳遞給模板:
return render(request, 'example.html', {'form': form, 'suggestions': suggestions })
然后在模板中:
{% for suggestion in suggestions %}
<img src="{{ suggestion.poster }}" onclick="autocompleteMovie({{suggestion}});" />
{% endfor %}
<script>
function autocompleteMovie(suggestion){
for (let field in suggestion)
document.getElementById('id_' + field).value = suggestion[field]
}
</script
將其與問題進(jìn)行比較,確實簡化了問題。
添加回答
舉報