Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when trying to render Folium map on Django Server

view.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)

my_map.html:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
</head>
<body>
{{ my_map }}
</body>

browser result:

folium.folium.Map object at 0x7f49d85662b0

im not sure how to approach getting the html/js to work on the browser after the user has submitted their input via the previous html form... I have seemed to look everywhere and there are a lot of similar problems with solutions but I could not get any to work!

Thanks!


1 Answers

This response is here to increase the google coverage for others who, like me, also experienced this problem when trying to render a Folium map within a Django template.

Your Code

Please see the comments inside each code block for how to render the map as expected.

views.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)

Template

<!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>

For more information see the Folium doc page here or this SO post.

Hope that helps.

like image 184
Daniel Michaels Avatar answered Oct 23 '25 05:10

Daniel Michaels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!