form disappearing after clicking on submit button on HTML - python

im doing this project which requires me to submit some forms and then return the value. However when i press the submit button the form disappear like as if the page got refreshed. Can any one help me? the code is in HTML
<div id="b2" class="containerTab" style="display:none;background:white">
<span onclick="this.parentElement.style.display='none'" class="closebtn">x</span>
<form method="POST">
<span style="float: left"><b>BTC amt >=: </b></span><center><b> Depth: <input type="range" name="rangeInput" min="0" max="20" onchange="updateTextInput2(this.value);"><input style="font-size:15px;" type="text" id="textInput2" value=""></b></center>
<input style="font-size:15px;" type="text" name=BTC amt><br>
<b>And <= :</b><br>
<input style="font-size:15px;" type="text" name="mdA">
 
<input style="font-size:20px;" name="BTCamt" type="submit" value="Submit"><br><br><br><br>
</form>
<div>
{{outBTC}}
</div>
</div>
This is the function im trying to run in this HTML
from flask import Flask, render_template, url_for, request
app = Flask(name)
#app.route("/")
def home():
return render_template('home.html')
#app.route("/", methods=['POST'])
def index():
# if form.validate_on_submit():
if 'transactionid' in request.form:
transactionaddr = request.form['transactionid']
newresult = runCypher(transactionaddr)
return render_template('home.html', outputresult=newresult)
elif 'BTCamt' in request.form:
transactionaddr = request.form['BTCamt']
newresult = runCypher(transactionaddr)
return render_template('home.html', outBTC=newresult)
def runCypher(transactionaddr):
from neo4j import GraphDatabase
uri = "bolt://localhost:7687"
user = "neo4j"
password = "123"
graphdb = GraphDatabase.driver(uri, auth=(user, password))
session = graphdb.session()
q1 = 'MATCH g=(n:out {addr: "'+transactionaddr+'"})-[*..3]-(m) RETURN g'
nodes = session.run(q1)
out = ""
for node in nodes:
out += str(node)
return out
if __name__ == '__main__':
app.run(debug=True)

The / route was declared twice. This should point you in the right direction..
#app.route("/", methods=['GET','POST'])
def index():
# if form.validate_on_submit():
if request.method == 'POST':
if 'transactionid' in request.form:
transactionaddr = request.form['transactionid']
newresult = runCypher(transactionaddr)
return render_template('home.html', outputresult=newresult)
elif 'BTCamt' in request.form:
transactionaddr = request.form['BTCamt']
newresult = runCypher(transactionaddr)
return render_template('home.html', outBTC=newresult)
return render_template('home.html')

Related

TypeError: . The function either returned None or ended without a return statement

view.py file
Since im new to flask. kindly help me out with this query
UPLOAD_FOLDER = 'static/uploads/'
app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
Migrate(app, db)
#view.route('/upload_image', methods=['GET','POST'])
def upload_image():
form = upload_form()
id = current_user.id
name_to_update = Users.query.get_or_404(id)
if request.method =='POST':
name_to_update.image = request.files['image']
Pic_filename = secure_filename(name_to_update.image.filename)
pic_name = str(uuid.uuid1()) + '_' + Pic_filename
saver = request.files['image']
name_to_update.image = pic_name
try:
db.session.commit()
saver.save(os.path.join(app.config['UPLOAD FOLDER'], pic_name))
flash('user profile updated successfully')
return render_template('account.html', form=form, name_to_update=name_to_update)
except:
flash('something is not working')
return render_template('account.html', form=form)
this is my account.html. i'm trying to get profile image of user and saving it to displaying in profile.
<div class="profile-content">
<div class="profile-contentimg">
<div>
<img src="static/img/apple.png" alt="" id="blah">
</div>
<form methods='POST' action="{{ url_for('view.upload_image') }}" class="dropzone">
<div class="profileupload">
<input type="file" name="filename" id="imgInp" >
<i class="fa fa-edit"></i>
<button type="submit" class="btn btn-primary">upload</button>
</div>
</form>
</div>
being beginner in programming with flask anything could be wrong.

How do you send a post request of a sliders value as its changing in Flask?

I have a flask app which should receive the value of a slider in index.html constantly but i'm not sure how to access the variable in the flask file.
The app.py flask file:
app = Flask(__name__)
#app.route('/', methods=('GET', 'POST'))
#app.route('/index', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
current = request.form['current']
print(current)
return render_template('index.html')
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
The html file:
<body>
<form method = 'POST'>
<div class="rangeslider">
<input type="range" min="1" max="100" value="50" class="myslider" id="sliderRange">
<p>
<span id="demo"></span>
</p>
</div>
<script>
const Http = new XMLHttpRequest();
var rangeslider = document.getElementById("sliderRange");
var output = document.getElementById("demo");
var current;
rangeslider.oninput = function() {
current = this.value;
if (current < 33){
output.innerHTML = 'Reverse';
current = 'reverse'
}
else if (current >= 33 && current <= 66){
output.innerHTML = 'Neutral';
current = 'neutral'
}
else if (current > 66){
output.innerHTML = 'Drive';
current = 'drive'
}
}
</script>
</form>
</body>
I've tried a lot of different things so some things in the code might be left over from those attempts but the basic question is, how do I access that html variable current in my python file?
You'll need to make a call to the server, where you will be processing this value (and possibly do something with it on the server, then return it to the browser, where you might display it somehow).
from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
#app.route('/', methods=('GET', 'POST'))
#app.route('/index', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
current = request.form['current']
print(current)
return render_template('index.html')
return render_template('index.html')
# I've added this method to receive slider updates
#app.route('/slider_update', methods=['POST', 'GET'])
def slider():
received_data = request.data
print(received_data)
return received_data
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
And here is the call to the server.
<body>
<form method = 'POST'>
<div class="rangeslider">
<input type="range" min="1" max="100" value="50" class="myslider" id="sliderRange">
<p>
<span id="demo"></span>
</p>
</div>
<script>
const Http = new XMLHttpRequest();
var rangeslider = document.getElementById("sliderRange");
var output = document.getElementById("demo");
var current;
rangeslider.oninput = function() {
current = this.value;
if (current < 33){
output.innerHTML = 'Reverse';
current = 'reverse'
}
else if (current >= 33 && current <= 66){
output.innerHTML = 'Neutral';
current = 'neutral'
}
else if (current > 66){
output.innerHTML = 'Drive';
current = 'drive'
}
// I've added this call to the server, which send 'current' value
Http.open('POST', '/slider_update')
Http.send(current)
}
</script>
</form>
</body>
You'll see values printed in the server log.

How can I transmit session in Django?

login.html
`<h2>Login</h2>
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
</form>
<input type="submit" value="login" />`
loggedin.html
`<h2>login success</h2>`
views.py
`def signin(request):
if request.method == "POST":
form = LoginForm(request.POST) #form = email, password
email_input = str(request.POST['email'])
password_input = str(request.POST['password'])
user_Qset = Profile.objects.filter(email = email_input)
if user_Qset is not None:
password_saved = str(user_Qset.values('password')[0]['password'])
if password_input == password_saved:
response = render(request, 'registration/login.html',)
request.session.modified = True
request.session['name'] = user_Qset.values('name')[0]['name']
request.session['email'] = user_Qset.values('email')[0]['email']
request.session['password'] = user_Qset.values('password')[0]['password']
return response
def loggedin(request):
if request.session.has_key('name'):
return HttpResponse("transmission success")
else:
return HttpResponse("transmission failed")`
I have a result 'transmission failed'. How can I transmit sessions I added?
When I push the login button, page url and templates should be changed and session be transmitted
When user log in, I want give user session keys(name, email, password)
I want to check session keys I gave is maintained well in another page

400 Bad Request: KeyError: 'username'

When testing this code i get the error "400 Bad Request: KeyError: 'username'" and i cant figure out why
Here is the code, i am using flask to do this
#app.route('/')
def index():
if 'username' in session:
username = session['username']
return 'Logged in as ' + username + '<br>' + \
"<b><a href = '/logout'>click here to log out</a></b>"
return "You are not logged in <br><a href = '/login'></b>" + \
"click here to log in</b></a>"
#app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action = "" method = "post">
<p><input type = text name = username/></p>
<p><input type = submit value = Login /></p>
</form>
'''
#app.route('/logout')
def logout():
#remove the session from username if it is there
session.pop('username', None)
return redirect(url_for('index'))
You're getting an error because there's no key username, most likely in the request.form object inside the if request.method == 'POST' block. This may be because of the way you're creating the form in HTML. You should put quotes around the field attributes, like:
<form action="" method="post">
<p><input type="text" name="username" /></p>
<p><input type="submit" value="Login"/></p>
</form>

how to add time to html from python method

this is part of a flask application. I would like to get the current time to output anywhere in the form of the html file.
I would like to add the method current_time() in flaskr.py to the anywhere in the from in the attached html file. Thanks!
flaskr.py
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
from datetime import date
import time
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
DATABASE = os.path.join(app.root_path, 'flaskr.db'), ##in real world apps use instance folders for databases instead
SECRET_KEY = 'development key',
USERNAME = 'admin',
PASSWORD = 'default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
#app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
def init_db():
db = get_db()
with app.open_resource('schema.sql', mode = 'r') as f:
db.cursor().executescript(f.read())
db.commit()
#app.cli.command('initdb')
def initdb_command():
init_db()
print('initialized the database.')
#app.route('/')
def show_entries():
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)
#app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
db = get_db()
db.execute('insert into entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']])
db.commit()
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))
#app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error = error)
#app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('show_entries'))
def current_time():
return date.today()
show_entries.html
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
<form action="{{ url_for('add_entry') }}" method=post class=add-entry>
<dl>
<dt>Title:
<dd><input type=text size=30 name=title>
<dt>Text:
<dd><textarea name=text rows=5 cols=40></textarea>
<dd><input type=submit value=Share>
</dl>
</form>
{% endif %}
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
{% else %}
<li><em> No entries so far</em>
{% endfor %}
</ul>
{% endblock %}
You can just use datetime.now() method:
from datetime import datetime
...
return render_template(... current_time = datetime.now())
...

Categories

Resources