I am making a web app using Python and have a variable that I want to display on an HTML page. How can I go about doing so? Would using {% VariableName %} in the HTML page be the right approach to this?
This is very clearly explained in the Flask documentation so I recommend that you read it for a full understanding, but here is a very simple example of rendering template variables.
HTML template file stored in templates/index.html:
<html>
<body>
<p>Here is my variable: {{ variable }}</p>
</body>
</html>
And the simple Flask app:
from flask import Flask, render_template
app = Flask('testapp')
#app.route('/')
def index():
return render_template('index.html', variable='12345')
if __name__ == '__main__':
app.run()
Run this script and visit http://127.0.0.1:5000/ in your browser. You should see the value of variable rendered as 12345
Related
The following code works perfectly from the .py file but I want to separate the HTML and put it in templates/index.html.
I suppose I have to use the render_template function in Flask to be able to return the same results.
# File dynamic_website.py
from owlready2 import *
onto = get_ontology("bacteria.owl").load()
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/')
def ontology_page():
html = """<html><body>"""
html += """<h2>'%s' ontology</h2>""" % onto.base_iri
html += """<h3>Root classes</h3>"""
for Class in Thing.subclasses():
html += """<p>%s</p>""" % (url_for("class_page", iri = Class.iri), Class.name)
html += """</body></html>"""
return html
I created a folder template and a file index.html. I used return render_template('index.html') but it doesn't work. What arguments do I have to add to the return_template function? "for Class in Thing.subclasses():" have to be in the .html file or .py file? What about the url_for function?
If you could edit the .py code and let me know what should I write exactly in the index.html file to have the same results it would be great.
UPDATE:
What I have done:
Python code
from flask import Flask, render_template
from owlready2 import *
from flask import Flask, url_for
onto = get_ontology("bacteria.owl").load()
app = Flask(__name__)
#app.route("/")
def ontology_page():
for Class in Thing.subclasses():
return render_template('index.html')
Html code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>{{ Class.name }}</h1>
</body>
</html>
You can't return a function multiple times. Whatever is returned, is the value of the function. This tutorial is in JS, but it implies the same concept as python does.
If you want the user to see a list of things on the html, do this. render_template('index.html', things=Thing.Subclasses()) This will give Jinja a list, where it can then for loop.
For html you can do this
{% for s in things %} {{ s }} is something {% endfor %}. Do anything you want with the s though, s is one subclass from the list.
I've been working myself through CS50 lately but now I'm struggling with my final project. One of the key elements is to allow users to upload images from an html website while the image will be further processed via an application.py. Overall I'll use flask.
Unfortunately this is where I'm already struggling. I tried all ways I could find to upload pictures and the result is always similar, when pressing the submit-button I receive an Internal Server Error message. I even copied code from youtube or forums which worked fine in the video but not in my IDE. Is it possible that the CS50 IDE blocks file uploads in general?
If not I isolate the problem to the code below and would highly appreciate if you could have a quick look. Probably it's a tiny problem I just don't get.
Code in my application.py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/upload", methods=["POST"])
def upload():
file = request.files["inputFile"]
return file.filename
if __name__ == "__main__":
app.run(debug=True)
Code in the index.html
<!DOCTYPE html>
<html lang="en">
<head>
FILE UPLOAD EXAMPLE
</head>
<body>
<div class="container">
<h1>File Input</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<div class="form-group">
<label for="inputFile">File input</label>
<input type="file" name="inputFile">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>
I tried to isolate the problem and one thing I found is that the form always returns "GET" when the submit button is pressed while it is specifically defined in the form method that return should be "POST.
Anyhow, thank you so much for any comments in advance!
Best,
Martin
It works when you have templates directory in your project structure.
myproject/
__init__.py
app.py
templates/
index.html
This is because Flask's default template path is templates.
if you want to change it to something else for ex 'my_templates' then you should override it while creating app.
app = Flask(__name__, template_folder='my_templates')
Btw there is no real DB/file store code return so it will just return you the filename as response.
I'm currently working on a web app in which I would like to display to the user whether they have visited the link already or not.
The code that displays the links is fairly simple, as seen below.
<ul>
<li>google</li>
<li>facebook</li>
<li>amazon</li>
</ul>
What I would like is to visualize that a link has been clicked by just adding a checkmark, or something along those lines, to the right of the link. How would I go about doing that? I'm working with Django for this project so a Django-specific solution would be great.
A very simple technique would be to use CSS :visited selector (if you don't want to use JavaScript). Check out this link for how you can use this selector in CSS.
You can basically add a checkmark in your HTML and set it's color same as background color (so that it doesn't show up). And, then change it to some other color when the link is visited. Check out the attached snippet.
a span {
color: white;
}
a:visited span {
color: black;
}
<ul>
<li>google<span>✓</span></li>
<li>facebook<span>✓</span></li>
<li>amazon<span>✓</span></li>
</ul>
I haven't used Django before, but I have some websites using Flask, so I can understand a few parts. I'll add my answer in Flask and hopefully you can translate that into Django. Sorry about that :/
I think you can make this work by using Jinja and some simple HTML.
I made some changes because links will just redirect you outside of your page, so your checkmarks wont be seen
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="/" method="POST">
<button name="google_" value="Google">Google</button>{% if _google %}✔{% endif %}
<br>
<button name="fb_" value="Facebook">Facebook</button>{% if _fb %}✔{% endif %}
</form>
</body>
</html>
the code in Flask would look like this:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def home():
if request.method == "POST":
if request.form.get("google_", False) == "Google":
_google = True
return render_template("test.html", _google=_google)
elif request.form.get("fb_", False) == "Facebook":
_fb = True
return render_template("Test.html", _fb=_fb)
return render_template("Test.html")
if __name__ == "__main__":
app.run(debug=True, host="localhost", port=5000)
Screenshots:
I didn't really made it look nice but it works :/
Again sorry for making it into Flask. I don't have any experience with Django.
I am new to Flask. I want to run my Python project, when the start button is pressed from the HTML page and display the string which is returned from the Python code, on the HTML page. I am using Python flask.
This is the HTML file with the button.(The name of the HTML file is json.html)
<!DOCTYPE html>
<html>
<body>
<h1>Smart Job Interviewer</h1>
<button type="button">Start the Interview</button>
</body>
</html>
Following is the Python flask file. newexecutiontest is my python file and run() is the function that I need to run. This function returns a string and I want to display it on the HTML page.
from flask import Flask
from TextToSpeech import newexecutiontest
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('json.html')
def dynamic_page():
return newexecutiontest.run()
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
When I run the code and load the web page it says that "This site can't be reached"
Can someone please help me to achieve the above task.
Thank you in advance.
Try changing the IP to localhost or 127.0.0.1
You should keep the html template under the folder /templates
You could make the button part of a form, so that it is routed back to your python module on click (just printing a string on button click could more easily be done with javascript, but I assume run() performs some logic as well). Also add some input field to the form so you can know it was submitted:
<form method="GET">
<input type="hidden" name="start">
<button type="submit">Start the Interview</button>
</form>
Now in the flask file, you can perform a basic check to see if "start", or whatever name you gave your input, exists in the get request arguments - which would mean the form was submitted. It is possible to pass arguments to an html file, so we will pass None if the form wasn't submitted or the desired string if it was:
from flask import request
#app.route('/')
def index():
return render_template('json.html', test_str=dynamic_page() if request.args.get("start") is not None else None)
And finally, you can check the value of test_str in the html file and print it accordingly, using the jinja templating engine. Logic is declared between {% and %}, while evaluations are declared between {{ and }}. Adding this to the html file where you want the string to be printed should work:
{% if test_str is not none %}
<p>{{ test_str }}</p>
{% endif %}
I'm working through the beginnings of a Flask tutorial and am trying to manually pass variables into a view template (called index.html) from the __init__.py file.
Here is the index.html file:
<html>
<head>
</head>
<body>
<h3>{{ title }}</h3>
<p>{{ paragraph }}</p>
</body>
</html>
and here is the __init__.py file:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("index.html", title = "Epic Tutorials", paragraph = "test")
if __name__ == "__main__":
app.run()
The view loads on the server when I replace the contents of the H3 and P tags with conventional words like you'd see on an HTML page without the curly braces, but I get a blank page when I add the curly braces, and am not sure how to rectify this.
__init__.py is special; it's how you demark a package.
You don't want to put your code there. Create a flat file for it instead. You could even rename __init__.py to something else, like init or index.