A string sample~text~11 is being passed as a parameter from index.html to plot.html using the Flask session.
I want to print the parameter using Brython on the page plot.html.
plot.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Plot</title>
<script type="text/javascript" src="../static/jquery/jquery-3.6.3.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script src="../static/brython/Brython-3.11.1/brython.js"></script>
<script src="../static/brython/Brython-3.11.1/brython_stdlib.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document
document <= "Hello World!"
document <= document.query['plot_param']
</script>
<h1>Plot page</h1>
<h3>{{plot_param}}</h3>
<h3 id="my_h3"></h3>
</body>
</html>
The above page is supposed to show the string sample~text~11 (see index.html) twice.
However, it is not doing what it was supposed to do. Brython is not parsing the parameter. Therefore, the string is shown only once (rather than twice).
How can I achieve what I want?
.
.
Additional Source Code:
app.py
from flask import Flask, session, render_template
from flask_socketio import SocketIO
from flask import request, redirect
async_mode = None
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.secret_key = "super secret key"
socketio_obj = SocketIO(app)
#app.route('/', methods=['GET', 'POST'])
def index():
print("index()...called...")
if request.method == "POST":
print("POST method used ...")
if request.form.get('submit_button1'):
session["unique_key_str"] = request.form['text1']
return redirect("/plot")
# end-if
# end-if
return render_template('index.html')
# end-def
#app.route('/plot', methods=['GET', 'POST'])
def plot():
print("plot()...called...")
return render_template('plot.html', plot_param=session["unique_key_str"])
if __name__ == '__main__':
socketio_obj.run(app, debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../static/jquery/jquery-3.6.3.js"></script>
<script type="text/javascript" src="../static/jquery/jquery.redirect.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
<form method="post" >
<input type="text" name="text1" value="sample~text~11" />
<input type="submit" name="submit_button1" value="Token value">
</form>
<h1>Index page</h1>
</body>
</html>
Related
main.py
`from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')`
home.html
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>HOME</h1>
hello
</body>
</html>`
hello.html
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>`
home.html is displaying while clicking the address
hello.html is not displaying while clicking the hyper link
Try this code
In main.py: Created new #app.route('/hi') that returns hello.html when called from home.html (see below)
In home.html: Changed href="hello.html" To href="/hi" to call that Flask route:
Flask Code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/hi')
def hi_there():
return render_template('hello.html')
app.run()
home.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>HOME</h1>
hello
</body>
</html>
hello.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
It looks like you're missing a route in your main.py file for the hello.html page. You need to add a new route that maps to the URL path /hello.html and returns the hello.html template.
I'm testing a little code to work, but I can't get it to work, this is the flask/python part:
#from weasyprint import HTML
import flask
import os
##
##html = HTML('text.html')
##html.write_pdf('invoice.pdf')
app = flask.Flask(__name__)
#app.route('/')
def hello_world():
today = datetime.today().strftime("%B %-d, %Y")
navigation = [1,2,3]
return flask.render_template('text.html',navigation = navigation,fecha = today)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
this is the test html, that im trying to work on:
<!doctype html>
<html>
<head>
welcome {{fecha}}
</head>
<body>
{% for item in navigation %}
this is a test, and hello {{item}}world!!!
{% endfor %}
</body>
</html>
but the output is this :
welcome {{fecha}} {% for item in navigation %}this is a test, and hello {{item}}world!!!
{% endfor %}""" (brs a let out intetionally)
this is the current folder structure:
what am I missing to make this work as intended?
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
fruits = ['๐', '๐', '๐', '๐', '๐', '๐', '๐', '๐ฅญ', '๐', '๐', '๐', '๐']
return render_template('index.html', fruits = fruits)
if __name__ == '__main__':
app.run(debug = True)
Your .html files should be in templates folder otherwise it will not work. (CASE SENSITIVE)
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flask App</title>
</head>
<body>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</body>
</html>
Folder Structure
Output Image
This is my first exercise in Flask and I would like to understand what I am doing wrong here.
I want to insert a text in a textbox and then visualize it in HTML
I have already looked many answers on StackOverflow, including this:
Set a python variable in flask with a button and javascript
This is my python code:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def my_form():
return render_template('test.html')
#app.route("/", methods=['GET','POST'])
def func_test():
if request.method == 'POST':
text = request.form['Value1']
return render_template('test.html', value1=text)
if __name__ == "__main__":
app.run(port=5000, debug=True)
and this is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form methods="POST">
<p>Login </p><br>
<p>Value1 <input type = "text" name = "Value1" /></p>
<p><input type = "submit" value = "submit" name = "submit" /></p>
</form>
input is {{value1}}
</body>
</html>
What I would like is that after the text is written in the textbox and the button is pressed, the text is printed after input is
Thanks
well, you can wrap your txt result in an if block that only shows when there is value
{% if value %}
input is {{value1}}
{% else %}
input is:
{% endif %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST">
<p>Login </p><br>
<p>Value1 <input type = "text" name = "Value1" /></p>
<p><input type = "submit" value = "submit" name = "submit" /></p>
</form>
input is {{value1}}
</body>
</html>
You're wanting to accept user input from an HTML form, and return that to the page. As far as I know you're going to need some kind of asynchronous Javascript (aka AJAX) to get this done.
Below is a full example modified from How to display a returned input in Flask using Ajax? for your situation.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
<p>Login </p><br>
<form action='/process' method="POST" autocomplete="off">
<div>
<p>Value1 <input type="text" name="value1" id="value1"></p>
<p><button type="submit">Submit</button></p>
</div>
</form>
<p id="input_is"></p>
</body>
</html>
Asychronous Javascript/AJAX, put this in a file called script.js in your static directory:
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
value1 : $('#value1').val(),
},
type : 'POST',
url : '/process'
})
.done(function(data) {
$('#input_is').text(data['response']).show();
});
event.preventDefault();
});
});
And your Flask route:
from flask import jsonify # add to your existing import
#app.route('/process', methods=['POST'])
def process():
user_input = request.form['value1']
print(user_input) # just for debugging purposes
return jsonify({'response' : user_input})
I have the following files on VS code and when I try to run them on my browser, it fails to identify that there is any reg.html template at all. What is the issue?
python file
from flask import Flask,
render_template, flash
app = Flask(__name__)
app.config["SECRET_KEY"] = "asdfghjkl"
#app.route("/")
def form():
return render_template("reg.html", title = "Form")
if __name__ == "__main__":
app.run(debug = True)
html file (reg.html)
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login/Signup - ((title)) </title>
<!-- Bootstrap CSS-->
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/bootstrap.min.css)' ))">
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/site.css') ))">
</head>
<body>
<div class = "container">
<div class = "row">
<div class = "col-md-5">
<h1 class = "text-center">Registration form</h1>
</div>
<div class = "col-md-2"></div>
<div class = "col-md-2"></div>
</div>
</div>
<!-- Javascript -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.js.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src = "((url for ('static', filename = 'js/bootstrap.min.js')))">`</script>`
</body>
</html>
To solve this question, create a folder named templates, which is where Flask looks for templates by default, then put the reg.html in this folder:
start the program and you will observe the results:
Detailed information about flask, you can refer to Flask Tutorial.
from flask import Flask, render_template, url_for, jsonify, request
from translate import Translator
en_ge = Translator("geo")
ge_en = Translator("en","geo")
app = Flask("Translator")
#app.route("/send",methods=["GET","POST"])
def send():
if request.method == "POST":
word = request.form["word"]
return render_template("translator.html",word=en_ge.translate(f"{word}"))
return render_template("index.html")
app.run()
I am trying to make translator with flask, but unfortunately I start learning it 10 minutes ago :). I am just trying to win a bet and make it as fast as I can. Googled but I keep receiving server internal error. How to fix it, please help
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Translator</title>
</head>
<body>
<h1>แจแแแงแแแแ แกแแขแงแแ</h1>
<form method="POST" action="/send">
<div class="form-group">
<input type="text" name="word">
</div>
<input class="btn btn-primary" type="submit" value="Translate">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>{{word}}</h1>
</body>
</html>
I think u miss template_folder param in Flask object creation, something like
app = Flask("Translator", template_folder="full_path_fo_a_folder_where_your_html_is_stored")