I am trying to write a program that reads a file and outputs it to the textarea. The user can then edit the file and then click the submit button in order to submit the changes.
Currently, I have a method of obtaining the user's input (request.form), however I do not know how to prepopulate the text area element.
Flask
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
#app.route('/')
def hello():
return render_template("index.html")
#app.route('/', methods=['POST'])
def submit():
return 'You entered: {}'.format(request.form['whitelist'])
if __name__ == '__main__':
app.run(host="localhost", port=8000, debug=True)
HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Index</title>
</head>
<body>
<h1 style="color: blue">Index</h1>
<p>This is an HTML file served up by Flask</p>
<p>Whitelist:</p>
<form action="{{ url_for('submit') }}" method="post">
<textarea id="whitelist" name="whitelist" rows="4" cols="50"></textarea>
<input type="submit">
</form>
</body>
</html>
So is their a method that exists such that one can prepopulate the textarea?
Example
my_file_data = read_my_file(file)
Flask.output(element_id = "whitelist", input = my_file_data)
Implementing Solution
Try the following changes in your code (i assume that your file is a .txt but it can work with other file types with some changes):
Flask
#app.route('/')
def hello():
with open('your_file') as f:
t=f.read()
return render_template("index.html", t=t)
HTML
<textarea id="whitelist" name="whitelist" rows="4" cols="50"> {{t}} </textarea>
Related
I have this very basic chat app, where everyone can chat in one huge group. And when I send messages, other people have to refresh their web page to see new messages. I am just wondering if anyone has any idea how to do this. By the way, the app is made with python Flask and HTML.
from flask import Flask, render_template, request, url_for, redirect
import database as db
app = Flask(__name__)
app.secret_key = 'ItDoesntMatter'
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('/index.html', messages=db.get_messages())
#Else
message = request.form['message']
db.send_message(message)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html 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>Chat</title>
</head>
<body>
{% for message in messages %}
<div>At {{ message[1] }}: <strong>{{ message[0] }}</strong></div>
{% endfor %}
<form method="POST" action="/">
<input type="text" placeholder="message" name="message">
<button type="submit" id="btn">Send</button>
</form>
</body>
</html>
I tried to do this with a turbo-flask, but it didn't work. I was also on google for like 1 hour and I didn't find anything.
I have been working on a web interface using Flask and having some issues with back button in browser as after logging out hitting it takes user back inside. I have found similar questions and tried their answers but the issue is not resolved. I am attaching a simple example kindly have a look at it.
Main
from flask import Flask, request,session, redirect, url_for, render_template
from os import urandom
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.secret_key = urandom(24)
#app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
session['Email id'] = request.form.get('Email Id')
Pass = request.form.get('Password')
try:
if session['Email id'] == 'KK#gmail.com' and Pass == 'KKK':
return render_template('Logged_in.html')
except:
return render_template('login.html')
return render_template('login.html')
#app.route('/sign_out')
def sign_out():
session.pop('Email id')
return redirect(url_for('index'))
#app.after_request
def add_header(r):
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True, threaded=True)
login.html
<!DOCTYPE html>
<html 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>Document</title>
</head>
<body>
<form action="{{ url_for('index') }}" method="POST" id="login" class="input-group">
<input type="text" class="input-field" placeholder="Email Id" required name="Email Id">
<input type="text" class="input-field" placeholder="Password" required name="Password">
<button type="submit" class="submit-btn" style="color: white;">Log in</button>
</form>
</body>
</html>
Logged_in.html
<h2>You are Logged in</h2>
<i class="fas fa-sign-out-alt"></i>Log out
Your problem is that when users push the back button their browser will re-do the POST request. You need to use the POST/redirect/GET pattern to prevent this. For this you need four endpoints in totalt:
GET / : Check in the session that the user is logged in and render Logged_in.html, otherwise redirect to /login.html
GET /login.html : Render login.html
POST /sign_in : Check username and password. If successful, update the session and redirect to /
POST /sign_out : Log out the user session and redirect to /login.html
Do not render templates in your POST endpoints, just make them manipulate the session and then redirect.
I have been developing a system but I recently have not been able to debug why I get this error
Method Not Allowed
The method is not allowed for the requested URL.
I have been developing a system
I assume the problem has to do with the post function not being allowed and being interrupted by something please assist me thx.
code:
python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def student():
return render_template('index.html')
#app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form['name']
print(result)
return "thank you for filling out this form"
if __name__ == '__main__':
app.run(debug = True)
file_object = open('transferfile.txt', 'a+')
name = "Gabriel"
age = "12"
gender = "male"
file_object.write(name)
file_object.write(" ")
data = file_object.read(100)
file_object.write(age)
file_object.write(" ")
file_object.write(gender)
file_object.close()
html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>venuefast</title>
</head>
<body>
<form class="logo" action="." method="post">fastvenue<br>
<hr>
<input type ="text" name="name" placeholder="name">
<br>
<button type="submit" value="submit">Submit</button>
</form>
</body>
</html>
Since the student function is rendering the form in index.html, it only makes sense that the student function accepts POST requests:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/',methods = ['POST', 'GET'])
def student():
if request.method == 'POST':
name = request.form['name']
return f"thank you for filling out this form {name}!"
return render_template('index.html')
#app.route('/result')
def result():
return 'this function does nothing yet'
if __name__ == '__main__':
app.run(debug = True)
an alternative, if you are planning to use student for something else, you can make result function renders index.html instead and also make it accept POST requests:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def student():
return 'this function does nothing yet'
#app.route('/result',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
name = request.form['name']
return f"thank you for filling out this form {name}!"
return render_template('index.html')
if __name__ == '__main__':
app.run(debug = True)
Try This in the HTML
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>venuefast</title>
</head>
<body>
<form class="logo" action="/result" method="POST">
<p>fastvenue</p>
<br>
<hr>
<input type ="text" name="name" placeholder="name">
<br>
<button type="submit" value="submit">Submit</button>
</form>
</body>
</html>
I'm trying to create a simple search tool that searches an existing Postgres table, using Flask, Jinja & SQLAlchemy.
It's all working, except when I search, the result that is displayed on my page is like this:
Note the bit i've circled, is what would be displayed if I did the same search just using Postgres/pgadmin. It's returning multiple random results.
Below is what would return by using Pgadmin:
Any ideas? My code is below.
App.py
from flask import Flask, render_template, request
from sqlalchemy import create_engine
from sqlalchemy import text
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='xxx://xxx:xxx#xxx:xxx/xxx'
engine = create_engine('postgresql+psycopg2://xxx:xxx#xxxr:xxx/xxx')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db=SQLAlchemy(app)
#app.route('/', methods=['GET', 'POST'])
def homepage():
if request.method == 'POST':
jn = request.form['jobnumber']
rp = db.session.execute(text("SELECT cost FROM public.options where cast(optionno AS VARCHAR) like :jn"), {"jn": f"%{jn}%"})
result_set = rp.fetchall()
return render_template('main.html', result_set=result_set, jn=jn)
else:
return render_template('main.html')
if __name__ == "__main__":
app.run(debug=True)
Main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>xxx</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
<p>xxx</p>
<form method="POST" id="jobnumber">
<input name="jobnumber" type="text" placeholder="jobnumber">
</form>
<table>
<td>
<h1> Results</h1>
<p>{{result_set}}</p>
</td>
</table>
</body>
</html>
How do I get it to only display the same as what PGAdmin would display?
You seem to be searching with %s in flask & without them in pgAdmin. If you need the same result in both, use the same query.
Enclosing the search string with % indicates to the SQL engine that you want to have values that contain your search string. Not just an exact match.
I am trying to create a site with a webform using Flask, but I keep getting a 500 error
Here is my template/main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/" method="post" name="login">
{{ render_field(form.test_form) }}<br>
<p><input type="submit" value="Sign In"></p>
</form>
</html>
Here is my init.py file
from flask import Flask, render_template
#import sqlite3
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html")
if __name__ == "__main__":
app.run()
Here is my form.py file
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
Why do I keep getting a 500 error? I cant figure it out.
Run in debug mode app.run(debug=True) to see more information in browser.
You should import form and send to template. You may need secret_key to use csrf. etc.
from form import LoginForm
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
#app.route('/')
def homepage():
return render_template("main.html", form=LoginForm())