Hi friend I want my template html file to display the loading spinner when session['train'] change. Here are the things I've tried but didn't work:
The html file:
<div class="messages">
{% block content%}
{% if session['training'] %}
<div class="spinner"><div class="double-bounce1"></div>
<div class="double-bounce2"><p style="font-weight:bold;font-size:16px;margin-left:-17px;color:white;">Training</p></div>
</div>
</div>
{% else %}
<div class="messages-content"></div>
</div>
<div class="message-box">
<textarea type="text" class="message-input" placeholder="Type message..."></textarea>
<button type="submit" class="message-submit">Send</button>
</div>
</div>
</div>
{% endif %}
{% endblock content%}
Python Code:
def retrain():
session['training']=True
app = Flask(__name__)
#app.route("/")
def home():
if session.get('logged_in'):
return render_template('index.html')
else:
return render_template('login.html')
#app.route('/login', methods=['POST'])
def login():
error = False
POST_USERNAME = str(request.form['username'])
POST_PASSWORD = str(request.form['password'])
Session = sessionmaker(bind=enginedb)
s = Session()
query = s.query(User).filter(User.username.in_([POST_USERNAME]), User.password.in_([POST_PASSWORD]) )
result = query.first()
if result:
session['logged_in'] = True ##for remember me function
flash('Login success')
return render_template('index.html')
else:
flash('Login failed!')
return render_template('login.html',error=True)
#app.route("/logout")
def logout():
session['logged_in'] = False
return home()
#app.route('/message', methods=['POST'])
def reply():
answer=response(request.form['msg'])
if "train" in answer:
retrain()
return jsonify( { 'text': answer})
The problem I'm encountering is that the spinner loader only display when I refresh my template page. I want whenever the variable "answer" in reply() contains "train", the template must auto reload and the spinner must be displayed!
The problem is that you are changing the session on the server in method reply(), but then returning json, and not returning anything that will cause the template to refresh or the session on the client to be updated.
Related
I'm working on a web app right now and I don't know how to display an error message when the user types in an invalid log in name. How do I go about this?
this is my login.html
{% block body %}
<h1>Login</h1>
{% if error %}
<p>Invalid Username</p>
{% endif %}
<form method="POST" action="{{ url_for('login') }}">
<input type="text" name="username" placeholder="Your Username">
<input type="submit" value="Submit">
</form>
<a href='{{variable6}}'>Sign Up</a>
{% endblock %}
this is my app.py
#app.route("/login", methods=["GET", "POST"])
def login():
if flask.request.method == "GET":
return flask.render_template("login.html")
if flask.request.method == "POST":
username = flask.request.form["username"]
cursor.execute(
"SELECT user_name FROM public.users WHERE user_name = %s", [username]
)
results = cursor.fetchall()
if len(results) != 0: # if a user exists, "log" them in
return flask.redirect(flask.url_for("main"))
else:
return flask.render_template("login.html")
I believe that your problem is that you are not defining what the "error" variable is, you could fix this by when you are returning the render_template in the last line of app.py, adding error=True, leaving you with this as your last line for app.py.
return flask.render_template("login.html", error=True)
As otherwise Jinja (the templating language you used in login.html) would not know what error and would get the type None as the value of error in the {% if error %} statement in login.html and since None is not equal to true, it would skip over the code you want to run.
Hope this helps :)
Website Link: Click Me
The "Next" button isn't submitting. My HTML Code is:
{% extends "layout.html" %}
{% block main %}
<div style='float:left;width:70%;'>
<div style='margin-top:200px;'>
<form method='POST' action='/login1'>
<input type='hidden' value="{{path}}">
<input style='width:800px;height:60px;font-size: 2em;' type='email' placeholder='Type your email to continue...' name='email' value="{{name}}">
<style>
.sub:hover{
border-style:none;
}
.sub{
border-style:none;
}
</style>
<input class='sub' type='submit' value='Next' style='height:75px;'>
</form>
</div>
</div>
<div style='float:left;width:20%;'>
<!--<img height="100%" src='static/assets/AccountBanner.png'>!-->
</div>
{% endblock %}
My Python Flask code is:
#app.route('/login')
def login():
username = request.cookies.get('login')
psw = request.cookies.get('psw')
if 'login' in request.args.get('path'):
return redirect('/login?path=/')
if username == None:
return render_template('login/index.html',path = request.args['path'])
with open('static/json/members.json') as a:
a = json.load(a)
found = False
for i in a:
if i["email"] == username:
if str(i["password"]) != str(psw):
return redirect('/')
else:
found = True
if found == False:
return render_template('login/index.html',path=request.args['path'])
return redirect('/')
#app.route('/login1', methods=['POST'])
def main1():
return render_template('password.html',redirect1 = "/login1"+request.args['path'])
What I am trying to do is asking the user for his/her email and then render a page asking for a password. However, the submit button isn't working. I am using action and method=POST submit.
Ok, I know why it didn't work.
Everytime I make an error (syntax error) OR I POST to a 404 page, I have a 404 and 500 function where it makes you login before viewing the 404/500 page. That's why it kept on redirecting to the original login page. It works now.
I'm having trouble getting error messages in Flask to render.
I suspect this is related to the blueprints. Previously, the logic seen in views.py was in the users blueprint, but I've since ported it over to the main blueprint. Anyhow, since then, I am unable to get error messages to render.
The specific line I think I'm having trouble with is:
self.email.errors.append("This Email is already registered")
project/main/views.py
#main_blueprint.route('/', methods=['GET', 'POST'])
#main_blueprint.route('/<referrer>', methods=['GET', 'POST'])
def home(referrer=None):
form = RegisterForm(request.form)
# prepares response
resp = make_response(render_template('main/index.html', form=form))
if form.validate_on_submit():
do_stuff()
return resp
project/main/index.html
<h1>Please Register</h1>
<br>
<form class="" role="form" method="post" action="">
{{ form.csrf_token }}
{{ form.email(placeholder="email") }}
<span class="error">
{% if form.email.errors %}
{% for error in form.email.errors %}
{{ error }}
{% endfor %}
{% endif %}
</span>
</p>
<button class="btn btn-success" type="submit">Register!</button>
<br><br>
<p>Already have an account? Sign in.</p>
</form>
project/user/forms.py
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
def validate(self):
print "validating"
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
print "not initial validation"
return False
user = User.query.filter_by(email=self.email.data).first()
print user
if user:
print self
print "error, email already registered"
self.email.errors.append("This Email is already registered")
return False
return True
When attempting to debug, the value for 'print user' from this is:
project.user.forms.RegisterForm object at 0x7fa436807698
Got it to work, #glls, you were correct.Rewrote the code as:
#main_blueprint.route('/', methods=['GET', 'POST'])
#main_blueprint.route('/<referrer>', methods=['GET', 'POST'])
def home(referrer=None):
# prepares response
resp = make_response(render_template('main/index.html', form=form))
if form.validate_on_submit():
do_stuff()
form = RegisterForm(request.form)
return resp
I want to make some kind of search engine for student's information by entering their first name in html input field, but I have some troubles with my code. I am using Flask with Python though.
Here is my project.py code:
#app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == "POST":
db = MySQLdb.connect(user="root", passwd="", db="cs324", host="127.0.0.1")
c=db.cursor()
c.executemany('''select * from student where name = %s''', request.form['search'])
for r in c.fetchall():
print r[0],r[1],r[2]
return redirect(url_for('search'))
return render_template('search.html')
Here is my search.html code:
{% extends "hello.html" %}
{% block content %}
<div class="search">
<form action="" method=post>
<input type=text name=search value="{{ request.form.search}}"></br>
<div class="actions"><input type=submit value="Search"></div>
</form>
</div>
{% for message in get_flashed_messages() %}
<div class=flash>
{{ message }}
</div>
{% endfor %}
{% endblock %}
When I hit Search button nothing happens, I checked database it has some data in it so it is not empty, I can't find where am I making a mistake, please help?
Make sure, action point to proper url
I think you render the form with wrong action for submitting the form.
Your version is using action="" and I guess, it shall be action="/search"
So your template shall be changed like:
{% extends "hello.html" %}
{% block content %}
<div class="search">
<form action="/search" method=post>
<input type=text name=search value="{{ request.form.search}}"></br>
<div class="actions"><input type=submit value="Search"></div>
</form>
</div>
{% for message in get_flashed_messages() %}
<div class=flash>
{{ message }}
</div>
{% endfor %}
{% endblock %}
Do not redirect out of your result
Your existing code is processing POST, but within first loop it ends up returning with redirect
#app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == "POST":
db = MySQLdb.connect(user="root", passwd="", db="cs324", host="127.0.0.1")
c=db.cursor()
c.executemany('''select * from student where name = %s''', request.form['search'])
for r in c.fetchall():
print r[0],r[1],r[2]
return redirect(url_for('search')) # <- Here you jump away from whatever result you create
return render_template('search.html')
Do render your template for final report
Your code does not show in POST branch any attempt to render what you have found in the database.
Instead of print r[0], r[1]... you shall call render_template()
Something like this
#app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == "POST":
db = MySQLdb.connect(user="root", passwd="", db="cs324", host="127.0.0.1")
c=db.cursor()
c.executemany('''select * from student where name = %s''', request.form['search'])
return render_template("results.html", records=c.fetchall())
return render_template('search.html')
I was asked to Create a simple Flask app which stores just a single text
field, On a single web page, and on which the user should see a form with the "message"
field. Below the form should be a list of existing messages in the
database. When user types something in the "message" field and submits the
form, the "message" should be saved to a table in SQLite. AND After the message is saved, user should come back to the page with the form and message list.
I am stuck at a POINT
I am not being able to SUBMIT the message
My page do retrieve messages from the database which is already stored in the database while I created it.
But Can SOMEONE please guide for the codes to SUBMIT the message filled in the form.
My message.html code is:
{% extends "template.html "%}
{% block content %}
<h2>You are in the Message Page</h2>
<br/>
<p><h4>In this page, You can view the Existing Messages and can also Submit your own message.</h4></p>
<br/><br/>
<h3>Enter Your Message:</h3><br/>
<form action="" method='POST'>
<dl>
<dt>Message:
<dd><input type="text" name=msg_msg maxlength=80 style="width:300px">*Maximum Length = 80
</dl>
<input type=submit value="Submit Message">
</form>
<h3>The Existing Messages:</h3>
{% for item in message %}
Msg_ID: <B>"{{ item.msg_id }}"</B><br/>Message: {{ item.msg_msg }} <br/><br/>
{% endfor %}
{% endblock %}
and my routes.py code for this is:
#app.route('/message')
def message():
g.db = connect_db()
cur = g.db.execute('select msg_id, msg_msg from msg')
message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template('message.html', message=message)
#app.route('/message', methods=['GET', 'POST'])
def message_1():
error = None
if request.method == 'POST':
for request.form['input_msg'] = text:
g.db = connect_db()
cur = g.db.execute('insert into msg_msg from msg')
message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template('message.html', message=message)
#error = 'Invalid Entry, Please Try Again.'
else:
# session['logged_in'] = True
return redirect(url_for('message'))
return render_template('message.html' , error=error)
Use 1 message view
#app.route('/message', methods=['GET', 'POST'])
def message():
cur = db.execute('select id,msg from msg_msg')
message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
if request.method == 'POST':
g.db = connect_db()
cur = g.db.execute('insert into msg_msg (msg) values (?)',request.form['input_msg'])
message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template('message.html' , message = message)
message.html
{% extends "template.html "%}
{% block content %}
<h2>You are in the Message Page</h2>
<br/>
<p><h4>In this page, You can view the Existing Messages and can also Submit your own message.</h4></p>
<br/><br/>
<h3>Enter Your Message:</h3><br/>
<form action={{ url_for('message') }} method='POST'>
<dl>
<dt>Message:
<dd><input type="text" name=msg_msg maxlength=80 style="width:300px">
</dl>
<input type=submit value="Submit Message">
</form>
<h3>The Existing Messages:</h3>
{% for item in message %}
Msg_ID: <B>"{{ item.msg_id }}"</B><br/>Message: {{ item.msg_msg }} <br/><br/>
{% endfor %}
{% endblock %}