【发布时间】:2020-11-12 13:18:24
【问题描述】:
2020 年 7 月 23 日更新
我有一个 Django 项目,我试图将一个值列表从 python 函数传递到我的“index.html”文件。此值列表来自我的 views.py 文件中的数据库查询
我的意见.py
def index_view(request):
context = {}
con=sqlite3.connect("db.sqlite3")
cursor=con.cursor()
db_query="SELECT distinct product_name from dboinvproduct"
cursor.execute(db_query)
result=cursor.fetchall()
con.close()
list_of_products = list(itertools.chain(*result))
context['product_names'] = list_of_products
return render(request, 'index.html', context)
然后在我的 index.html 正文中
function loadFunct(){
var products = "{{product_names|safe}}";
alert(products);
}
警报显示以下字符串:
['product a', 'product b', 'product c', 'product d']
这比我以前更接近了。问题是,这是一个看起来像数组的字符串...这意味着这不适用于我的应用程序...我需要它采用数组的形式。
最好的方法是什么?我已经阅读了有关 python 方面的 json_dumps 的信息,但我得到了一个 typeError ,因为它需要一个字典......
【问题讨论】:
标签: javascript python html django templates