这里是 Django 新手:我的目标是将 Folium 集成到 html 页面中。所以我现在拥有的是:
polls/views.py
def show_map(request):
#creation of map comes here + business logic
m = folium.Map([51.5, -0.25], zoom_start=10)
test = folium.Html('<b>Hello world</b>', script=True)
popup = folium.Popup(test, max_width=2650)
folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m)
context = {'my_map': m}
return render(request, 'polls/show_folium_map.html', context)
polls/urls.py
urlpatterns = [
path('show_my_map', views.show_map, name='show_map'),
]
和show_folium_map.html
<h1>map result comes here</h1>
{{ my_map }}
问题是我得到了 map 的“to_string”值(我向你保证我看到了)。那么我如何才能以实际看到 map 并定义大小的方式集成 map 呢?
最佳答案
为了真正将 folium 包含到自定义 django 模板中,您必须先渲染图形,然后再将其添加到上下文中(这将递归地将 map 的所有部分加载到图形中)。之后在您的模板中,您必须通过调用它们的渲染函数来分别访问图形的标题、html 和脚本部分。此外,这些部分必须由 django 模板标记标记为“安全”,以允许插入 html。请参见下面的示例。
示例:
views.py:
import folium
from django.views.generic import TemplateView
class FoliumView(TemplateView):
template_name = "folium_app/map.html"
def get_context_data(self, **kwargs):
figure = folium.Figure()
m = folium.Map(
location=[45.372, -121.6972],
zoom_start=12,
tiles='Stamen Terrain'
)
m.add_to(figure)
folium.Marker(
location=[45.3288, -121.6625],
popup='Mt. Hood Meadows',
icon=folium.Icon(icon='cloud')
).add_to(m)
folium.Marker(
location=[45.3311, -121.7113],
popup='Timberline Lodge',
icon=folium.Icon(color='green')
).add_to(m)
folium.Marker(
location=[45.3300, -121.6823],
popup='Some Other Location',
icon=folium.Icon(color='red', icon='info-sign')
).add_to(m)
figure.render()
return {"map": figure}
templates/folium_app/map.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{{map.header.render|safe}}
</head>
<body>
<div><h1>Here comes my folium map:</h1></div>
{{map.html.render|safe}}
<script>
{{map.script.render|safe}}
</script>
</body>
</html>
关于python - Django 和 Folium 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50517620/