Is something wrong with render_template? [duplicate] - python

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 4 years ago.
I'm new to flask (but not new to Python) and I've been following Corey Schafer's YouTube tutorial on setting things up. I've done everything almost as Corey did in the videos. I'm working with Visual Studio Code on Mac instead of Sublime, which is the only difference.
When I get to the step of using the render_template function to execute basic html files, something is going wrong and I'm getting all kinds of errors. What am I missing?
My flask_blog.py program:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
#app.route("/home")
def home():
return render_template('home.html')
#app.route("/about")
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
home.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Home Page</h1>
</body>
</html>
about.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>About Page</h1>
</body>
</html>
And here is what I'm getting when I try navigating to the home page:
Screenshot 1/2
Screenshot 2/2

Ensure that you are storing the html files in a subdirectory called templates:
parentfolder
templates
home.html
about.html
flask_blog.py \\this is the file that contains the route declarations

Related

Flask doesn't show an image

So I want to show a diagramm on my HTML page using Flask but when I run my website, then I don't see the image. I know there are a couple of similar questions here, but I'm just stuck with it.
Here is my Python Code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('test.html')
if __name__ == "__main__":
app.run(debug=True)
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Diagramm</h1>
<img src="{{url_for('static', filename='test.jpg')}}" alt="Here should be a picture"/>
</body>
</html>
And here is my file path:
/home/pi/flask
/static
/test.jpg
/templates
/test.html
website.py #This is the Programm

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.

Can not go to another page using url_for inside html tag in Flask [duplicate]

This question already has answers here:
Python Flask Render Text from Variable like render_template
(4 answers)
Closed 3 years ago.
I can not go to about_me page from the index page.
Error :
The requested URL was not found on the server.
and got url like "http://127.0.0.1:5000/%7B%7B%20url_for('about')%20%7D%7D".
from flask import Flask, redirect, url_for
app = Flask(__name__)
#app.route('/')
def index():
return '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<p>welcome home</p>
about
</body>
</html>
'''
#app.route('/about')
def about_me():
return 'about me'
if __name__ == '__main__':
app.run(debug=True)
The formatting you're using to insert the url_for the about me page, namely:
about
Will only work inside of a Jinja template. Those templates get processed by the template engine before the response is returned, and during that processing the notation with the two braces {{ something }} gets recognized and interpreted differently.
Here however, you are not using this notation in a Jinja template, you are using it it in a normal string, a string that does not get processed and thus does not have anything replaced.
The correct way to achieve what you want, in this case would be to parameterize the string and pass the link through formatting. E.g:
#app.route('/')
def index():
return '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<p>welcome home</p>
about
</body>
</html>
'''.format(about_me=url_for('about_me'))
Hope this helps!

File upload using Flask without refresh

I have user interface (angularJS) in which i need to upload a file without refreshing the page.Currently we are using Flask as web application framework.
I changed the index.html to below format so that without using form tags i am trying to read the uploaded file and store it.
Using ngclick method how to read the file from app.py ?
The following is the code snippet(index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask Bucket List App</title>
<link href="http://bootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
</head>
<body>
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload file</button>
</div>
</body>
</html>
code snippet of app.py
from flask import Flask, render_template, json, request
app = Flask(__name__)
#app.route('/')
def main():
return render_template('index.html')
#app.route('/upload/')
def upload_file():
print('uploaded file ',request.FILES['file1'].read())
return render_template('signup.html')
I tried various options but i could not find feasible option.
Thanks
vijay

How can I read request values received with Python?

I want to make a simple python script to be run in my server. What it's supposed to do is receive requests and return values according to requests it received.
I want to access the script with a way like http://example.com/thescript.py?first=3&second=4.
and make the script to read the first and second and to do jobs with the values.
How could I do this?
The easiest way is to use Flask:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
first = request.args.get('first')
second = request.args.get('second')
return render_template('index.html', first=first, second=second)
if __name__ == '__main__':
app.run()
And the template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
First: {{ first }}
<br />
Second: {{ second }}
</body>
</html>
This code will simply print the two parameters provided.

Categories

Resources