Error when trying to render Folium map on Django Server - python

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!

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.

Map objects have a render method which render its html representation.
You can try directly:
<body>
{{ my_map.render }}
</body>
Or you can use the Map.render method to implement a custom inclusion tag, that way you can pass arguments to the render method. See this for reading more about inclusion and custom tags.
# The template tag.
for django.template import Library
register = Library()
#register.inclusion_tag
def render_map(map_object, **kwargs):
return map_object.render(**kwargs)
In your template:
<body>
{% render_map my_map some_arg1=arg1 some_arg2=arg2 %}
</body>

Related

How to render html for variables in Flask render_template [duplicate]

This question already has answers here:
Passing HTML to template using Flask/Jinja2
(7 answers)
Closed 9 months ago.
I am using Flask render_template method to render my html page as below:
render_template('index.html', content="<div>Hello World!</div>")
My index.html is:
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
{{content}}
</body>
</html>
My page is replacing the content variable, but it is rendering <div>Hello World!</div> as text.
Is there a way to render html from render_template context variables?
Flask turns on Jinja's autoescape feature. Quoting the manual on how to disable it:
There are three ways to accomplish that:
In the Python code, wrap the HTML string in a Markup object before passing it to the template. This is in general the recommended way.
Inside the template, use the |safe filter to explicitly mark a string as safe HTML ({{ myvariable|safe }})`
Temporarily disable the autoescape system altogether.
If you do not require passing in HTML tags into the template, you may simply do something that looks like this
Template
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
<div>
{{content}}
</div>
</body>
</html>
Python code
#app.route('/')
def home():
render_template('index.html', content="Hello World!")
This should be perfectly fine. If you do want to add html into your content variable, then the answer by #Ture Pålsson is the best way forward.

Calling python function in html page

Ive made a flask script which runs fine however im trying to display some values in a table on another html page which for some reason is not happening.
i've already tried going through jinja2 documentation and a few other answers but it didn't help much.
the flask file.py
from flask import Flask,render_template,request
app = Flask(__name__)
from webscraper import keeda,display_tbl
#app.route('/', methods=['POST', 'GET'])
def scraper():
if request.method == 'POST':
url = request.form['url']
df=keeda(url)
return render_template(('completed.html',display_tbl(df)))
else:
return render_template('index.html')
if __name__ == '__main__':
app.run()
the completed.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ display_tbl(df) }}
</div>
</body>
</html>
here's the error: jinja2.exceptions.UndefinedError: 'display_tbl' is undefined
i wanted to display a table with values on this page.
You are expecting more than what jinja2 can do for you. Please understand jinja2 is just a way to render templates which are eventually html and javascript, nothing fancy. So, in your case you cannot pass a Python function to your jinja2 template and expect that to run fine. What you can do here is to pass the data returned by display_tbl while rendering template like this:
def scraper():
...
return render_template(('completed.html', data=display_tbl(df))) # data= is important because this is how you are going to access your data in the template
…
def display_tbl(df):
… # Here you should be returning the data you want to display - a list or dict
In the template
<html>
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ render_data() }}
</div>
<script>
var d = data | tojson
function render_data() {
// implement the logic to handle how your data should be rendered
}
</script>
</body>
</html>
This is just a rough idea but as you can see you need to change the way you are perceiving jinja2 templates and their interaction with Python or Flask backend.

Insert python string into Django template context with markup

If I render a static image in the .html template it works. But if I provide the static markup string as dictionary value to the template (the context), it will not work. It seems to be something to do with string formatting and not allowing me to use {% %} the way I need to. I have tried:
1. .format()
2. escaping the percent characters
3. raw strings
4. concatenation
5. autoescape
6. | safe
and a number of other things
Basically, I am constructing a multi-line string in view.py with '''{% %}''', and then rendering a template with this string as the context. Python 2.
UPDATE
Simple non-working example:
view.py
def index(request):
image_insert = ''
images = ['image1.jpg', 'image2.jpg', 'image3.jpg']
for image in images:
image_insert += '<img src="{}">'.format(image)
context = {'insert': image_insert}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
First Image
<img src={% static "image.jpg" %}>
Second Image <!-- does not work -->
{{ image_insert | safe }}
</body>
</html>
Page Source:
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
<img src=/static/mqdefault.jpg>
Second Image
<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">
</body>
</html>
Obviously, there is a difference. This is Django 1.11 btw if it makes a difference.
You can also achieve this by passing img source from the view as follow:
views.py
from django.contrib.staticfiles.templatetags.staticfiles import static
def index(request):
context = {'image_src': static("image.jpg")}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
<img src="{{ image_src }}">
</body>
</html>
UPDATE: Multiple Images
You can generate markup with multiple images and pass it in the context as seen in the views.py:
views.py
from django.contrib.staticfiles.templatetags.staticfiles import static
def index(request):
images = [static('image1.jpg'), static('image2.jpg'), static('image3.jpg')]
images_html = "".join([
"<img src={image}>".format(image=image)
for image in images
])
context = {'images_html': images_html)}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
Now, your updated index.html will be:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
{{ images_html|safe }}
</body>
</html>
Hope it helps.
working code:
def index(request):
context = {'image_insert': "image.jpg"}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
First Image
<img src="{% static "image.jpg" %}">
Second Image <!-- does not work -->
<img src="{% static image_insert %}">
</body>
</html>

Unable to send variable from views to html python

Am Unable to sent the temp_k variable from my views to index.html. I have made a request from weather API and trying to pass it to my html.
Please suggest how we are supposed to send the variable from views to template.
views.py
from django.template.loader import render_to_string
import requests
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
my_dict = {'insert_me': "From andu.py"}
return render(request, 'mywebapp/index.html', context=my_dict)
def temperature(request):
#zip=requests.form['zip']ss
r=requests.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22')
json_object=r.json()
my_dict1={'temp_k' :json_object['main']['temp']}
return render(request,'mywebapp/index.html', context=my_dict1)
index.html
<!DOCTYPE html>
{% load staticfiles%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hey</title>
<link rel="stylesheet" href={% static "cs/style.css" %}/>
</head>
<body>
<h1>This is the Header</h1>
<img src="{% static "images/youownme.jpeg" %}" atl="Uh Oh">
<h2> Temperature:{{temp_k}}</h2>
</body>
</html>
I have tried your code and it works fine so you may want to check if you are rendering the right HTML files maybe, i've changed your code to make sure it's working and it is
my_dict1={'temp_k' :json_object['wind']['speed']}
sorry but I cant write a comment yet!
Use render like this :
return render(request,'mywebapp/index.html',{'context':my_dict})

How to get html passed as a variable from python flask into html?

In this example:
from flask import Flask, render_template, redirect, session
app = Flask(__name__)
app.secret_key="secret"
#app.route('/')
def landing():
session['results']="<p>Test one</p>"
session['results']+="<p>Test two</p>"
results=session['results']
return render_template('index.html', results=results)
app.run(debug='True')
In my html, I have something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Game</title>
</head>
<body>
{{ results }}
</body>
</html>
The results are an html page that does not interpret the tags. So, I get a page that looks like this:
<p>Test One</p><p>Test Two</p>
You could escape the HTML:
{{ results|safe}}
or in Python
import jinja2
results = jinja2.escape(results)
The framework is escaping the HTML in the results variable to prevent security holes. Ideally you want to keep the HTML in the template and not be passed in via the variables. The best way to achieve what you want is to iterate over the values in results variable and wrap it in p tags in the template. This can be done like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Game</title>
</head>
<body>
{% for result in results %}
<p>{{ result }}</p>
{% endfor %}
</body>
</html>
The templating language is Jinja2, and you can read about that here: http://jinja.pocoo.org/
Try this:
from flask import Markup
results = Markup(results)

Categories

Resources