Python flask - change template when a button is clicked [duplicate] - python

This question already has answers here:
TypeError: 'dict' object is not callable
(8 answers)
Get the data received in a Flask request
(23 answers)
Closed 2 years ago.
I want to change templates when a button is clicked.
Here is my python code:
#app.route("/", methods = ['POST', 'GET'])
def my_forum_post():
if request.method == 'POST':
if request.form['myBtn'] == 'Sign in':
return render_template('new_profile.html')
And here is my HTML code:
<form method = 'POST'>
<input type="button" name="myBtn" value="Sign in">
</form>
And the template which i want to swich to is called: new_profile.html

The problem is with this line of your code:
text = request.form('input')
Change it to this:
text = request.form['input']
or this
text = request.form.get('input')

Related

How to add data to a specific user flask-SQLAlchemy [duplicate]

This question already has answers here:
Flask-SQLalchemy update a row's information
(8 answers)
Closed 11 months ago.
Hello I am making a blogging website with flask, flask-sqlalchemy, and flask-login. I am trying to figure out a way to add optional data such as a role after the account creation.
This is as far as I have gotten:
#app.route('/addpinfo', methods=["POST", "GET"])
#login_required
def accountinfo():
if request.method == "POST":
username = current_user.username
job = request.form.get("role")
user_job = Loginbase(job=job)
db.session.add(user_job)
db.session.commit()
return redirect(url_for("homebase"))
else:
return render_template("accountspecs.html")
Here is what the HTML looks like:
<form method="post">
<script src="{{url_for('static', filename='js/accountspecs.js')}}"></script>
<input class="dissapointment form-box" type="text" placeholder="Write a hobby or job title"name="role"><br>
<button class="cool-sub" type="submit" name="submit">Add Role Info</button>
</form>
Does anyone know where I can go from here? I have been having trouble trying to find a way to add that element to the account the user is currently using.
Thank you for any help ahead of time.
The solution that worked with my code was:
#app.route('/addpinfo', methods=["POST", "GET"])
#login_required
def accountinfo():
if request.method == "POST":
user = current_user
job = request.form.get("role")
user.job = job
db.session.commit()
return redirect(url_for("homebase"))
else:
return render_template("accountspecs.html")
This allowed for my role system to work. I thank Patrick for all of their help.

displaying flask input() to a html template [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 12 months ago.
how can i display an input to my web application? Ive tried many ways but not succesfully...
import random
import re
from flask import Flask, render_template
app = Flask(__name__)
app.debug = True
#app.route("/")
def index():
return render_template("play.html")
#app.route("/hangman")
def hangman():
answer = input("Hi, wanna play? Y/N: ")
return render_template("game.html", answer=answer)
In game.html template you should put an input tag:
<form method="post" action="/want-to-play">
<input type="text" placeholder="Do you want to play?" />
<input type="submit" value="OK"/>
</form>
Then just put an endpoint /want-to-play in your flask app with what you want to do.

Python Flask: How to save the data from page [duplicate]

This question already has answers here:
Insert or write data to .txt file with flask
(2 answers)
Closed 1 year ago.
Is anyone wrapping up flask in python well? I have a registration form but I don't know how to save the data from that page, like name and password, so I can read it later.
Save to a separate file of type:
file = open(file.txt)
file.write(username + password)
does not work when I already host the page.
Firstly, can you provide your code? What would you like to create? Is it a simple web application that requires registration and authorization or is it just a form from which you would like to take some data?
Secondly, there is some good tutorials in the Internet about Flask registration. Moreover, you can read this. Here there is a Flask student book. You can search for something different if this tutorial will not actual and proper for you.
Thirdly, about saving data in the textual file .txt from flask app. You can check this answer.
UPD. For the last variant with file.
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/', methods = ['POST'])
def get_data():
login = request.form['login']
password = request.form['password']
if request.method == 'POST':
with open('data.txt', 'a+') as f:
f.write(str(login) + ' ' + str(password) + '\n')
return render_template("index.html")
if __name__ == '__main__':
app.run(debug = True)
templates/index.html
<html>
<body>
<form action="" method="POST">
<p>Login <input name="login" /></p>
<p>Password <input name="password" /></p>
<p><input type="submit"></p>
</form>
</body>
</html>

BadRequestKeyError [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 4 years ago.
Multiple questions have been asked with a similar error on SO. I have tried all of the solutions but still keep getting a beautiful error:
werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'username'
Below is my html form:
<form action='/login' method = "GET">
<label>Name: </label>
<input name="username" type="text">
<input type="submit" name='submit' value='submit'>
</form>
Here is the function that deals with the form data:
#app.route('/login', methods = ['GET'])
def login():
if request.method == "GET":
un = request.form['username']
return un
I have learned Bottle and transitioning towards Flask.
So far, I have tried the following:
1) GET to POST
2) request.form.get('username', None)
3) Add POST reason to the function route without any rhyme or reason.
Can somebody help me out?
You need to change the method (GET to POST) in the html file and add the method in the decorator #app.route too. Do not forget that in this case a return (GET) is required to render the html file.
#app.route("/login", methods = ['GET', 'POST'])
def login():
if request.method == "POST":
# import pdb; pdb.set_trace()
un = request.form.get('username', None)
return un
return render_template('form.html')
Tip: Learn about pdb to debug your programs more easily.
https://realpython.com/python-debugging-pdb/
https://docs.python.org/3/library/pdb.html
no need to change your form action method. but when you use GET method for sending form data your data is transmitted as URL variables and you need to read data this way:
if flask.request.method == 'GET':
username = flask.request.args.get('username')
and if you change the method to POST, read content as below:
if flask.request.method == 'POST':
username = flask.request.values.get('username')

Handling POST method for two app routes to same function [duplicate]

This question already has answers here:
How do I get the different parts of a Flask request's url?
(4 answers)
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Closed 4 years ago.
How can i get something like this to work?
#app.route('/client_progress')
#app.route('/client_update', methods=['POST', 'GET'])
def func_1():
if (//app.route == client_progress)
if request.method == 'POST':
return 'hello world'
elif (//app.route == client_update)
if request.method == 'POST':
return 'Good World'
I would like to have two app routes to same function and be able to respond back to appropriate route.
is this possible? if yes, please share the example.

Categories

Resources