尝试在 Django 服务器上渲染 Folium 地图时出错

sme*_*kaa 4 python django dictionary render folium

视图.py

map = folium.Map(location=[df['latitude'].mean(), 
df['longitude'].mean()],tiles="cartodbpositron",zoom_start=12)

map.save("map.html")

context = {'my_map': map}

return render(request, 'my_map.html', context)
Run Code Online (Sandbox Code Playgroud)

my_map.html:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
</head>
<body>
{{ my_map }}
</body>
Run Code Online (Sandbox Code Playgroud)

浏览器结果:

folium.folium.Map object at 0x7f49d85662b0
Run Code Online (Sandbox Code Playgroud)

我不确定在用户通过之前的 html 表单提交输入后如何让 html/js 在浏览器上工作...我似乎到处都在寻找,并且有很多类似的解决方案问题,但我可以没有人去工作!

谢谢!

Dan*_*els 5

此回复是为了增加像我一样在尝试在 Django 模板中渲染 Folium 地图时也遇到此问题的其他人的 google 覆盖率。

你的代码

请参阅每个代码块内的注释,了解如何按预期渲染地图。

视图.py

map = folium.Map(location=[df['latitude'].mean(), 
df['longitude'].mean()],tiles="cartodbpositron",zoom_start=12)

map.save("map.html")

# {'my_map': map} will output the object, which is what you are seeing
# to rectify this we need to turn it into an iframe which 
# the template can then render.
context = {'my_map': map} # change to {'my_map': map._repr_html_()}

return render(request, 'my_map.html', context)
Run Code Online (Sandbox Code Playgroud)

模板

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
</head>
<body>
# after making the change in our views.py this will return the html but
# the template will not render it as expected because it is being escaped.
# You must declare it 'safe' before it will be rendered correctly.
{{ my_map }} # change to {{ my_map | safe }}
</body>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此处的Folium 文档页面或SO 帖子。

希望有帮助。