I am having another issue with CS50 finance and would really appreciate some help.
So I am working on the BUY section, and I have implemented an extra step, where you type in what stock you want, and how much of it you want, then it takes you to a new html page to confirm that you want to buy the stock. This pages tells you how many shares you will buy, how much it costs, and what your cash balance will be after you buy the shares.
My issue is that when I go to actually buy the stock on the confirmation page, I get errors that say my variables (specifically balance, shares and price_per_share) are undefined and I cannot figure out why. I will attached the relevant portions of my code below. Thanks again.
Application.PY:
#app.route("/buy", methods=["GET", "POST"])
#login_required
def buy():
if request.method == "POST":
quote = lookup(request.form.get("symbol"))
if quote == None:
return apology("invalid symbol", 400)
try:
shares = int(request.form.get("shares"))
except:
return apology("shares must be a positive integer", 400)
if shares <= 0:
return apology("can't buy less than or 0 shares", 400)
users= db.execute("SELECT cash FROM users WHERE id= :user_id", user_id=session["user_id"])
cash_remaining = users[0]["cash"]
price_per_share = quote["price"]
total_price = price_per_share * shares
balance = cash_remaining-total_price
symbol=quote["symbol"]
return render_template ("confirmation.html", cash_remaining=cash_remaining, price_per_share=price_per_share, total_price=total_price,shares=shares, symbol=symbol, balance=balance)
else:
return render_template ("buy.html")
#app.route("/confirmation", methods=["GET", "POST"])
#login_required
def confirmation():
if request.method == "POST":
db.execute("UPDATE users SET cash = cash = :balance WHERE id = :user_id", balance=balance, user_id=session["user_id"])
db.execute("INSERT INTO transactions (user_id, symbol, shares, price_per_share) VALUES(:user_id, :symbol, :shares, :price_per_share)",
user_id=session["user_id"],
symbol=request.form.get("symbol"),
shares=shares,
price_per_share=price_per_share)
flash ("Bought!")
return render_template("index.html")
else:
return render_template("confirmation.html")
here is my buy.html code in case needed:
{% extends "layout.html" %}
{% block title %}
Quote
{% endblock %}
{% block main %}
<form action="/buy" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="Symbol" type="text" required/>
</div>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="shares" placeholder="Shares Wanted" type="number" min="1" required />
</div>
<button class="btn btn-primary" type="submit">Get Price</button>
</form>
{% endblock %}
and finally my confirmation.html:
{% extends "layout.html" %}
{% block title %}
Quote
{% endblock %}
{% block main %}
<form action="/confirmation" method="post">
<p>Stock Symbol ={{symbol}}</p>
<p>Shares to be purchased = {{shares}}</p>
<p>Total Transaction Cost {{total_price | usd}}</p>
<p>Current Cash = {{cash_remaining | usd}}</p>
<p>Balance after transaction = {{balance |usd}}</p>
<button class="btn btn-primary" type="submit">Buy</button>
</form>
{% endblock %}
There are no values submitted with the form in confirmation.html. Some options:
add the data to the session array
create hidden input controls to carry the data back to the server
give the button element a name, and a json encoded string of the values that confirmation will need as its value.
The confirmation route doesn't (try to) get any values from the form (eg request.form.get).
I am working on Malicious Webpage Detection using logistic regression and have used a dataset from kaggle. Using flask and html i want to predict whether the url is good or bad.
this is the code snippet in app.py
if request.method=='POST':
comment=request.form['comment']
X_predict1=[comment]
predict1 = vectorizer.transform(X_predict1)
New_predict1 = logit.predict(predict1)
new = New_predict1.tolist()
new1 = " ".join(str(x) for x in new)
return render_template('result.html',prediction=new1)
this code i have written in result.html
{% if prediction == 1%}
<h2 style="color:red;">Bad</h2>
{% elif prediction == 0%}
<h2 style="color:blue;">Good</h2>
{% endif %}
Why the results (Bad/Good) are not being displayed for this code?
I assume in app.py:
New_predict1.tolist() returns a list.
" ".join(str(x) for x in new) returns a concatenated string value.
In result.html:
prediction == 1 or prediction == 0 compares the value of prediction to integer. But from app.py you are sending a concatenated string value. So, this Bad or Good will not be shown in template.
You need to use String comparison like: prediction == "some constant"
I reproduced your scenario:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods = ['GET', 'POST'])
def home():
if request.method == "POST":
comment=request.form.get('comment')
X_predict1=[comment]
# Do some operations
#predict1 = vectorizer.transform(X_predict1)
#New_predict1 = logit.predict(predict1)
#new = New_predict1.tolist()
#new1 = " ".join(str(x) for x in new)
# Dummy list
new = [1, 2, 3]
# " ".join() returns a string
new1 = " ".join(str(x) for x in new)
return render_template('result.html', prediction=new1)
return render_template('result.html')
if __name__ == "__main__":
app.run(debug=True)
result.html:
<html>
<head>
<title>Home</title>
</head>
<body>
<form action="/" method="post">
Comment:
<input type="text" name="comment"/>
<input type="submit" value="Submit">
</form>
<h3>Prediction Result</h3>
{% if prediction == 1 %}
<h2 style="color:red;">Bad</h2>
{% elif prediction == 0 %}
<h2 style="color:blue;">Good</h2>
{% else %}
<h2 style="color:black;">{{prediction}}</h2>
{% endif %}
</body>
</html>
Output:
As you can see the else block is triggered in the template as both if and elif block is skipped.
What I am basically trying to do is capture data into my middleware from front end, so that I can track the users activity. User activity refers to buttons clicked and data entered into a form.
So I am done with the button part but stuck on getting data filled in the form by the user. I need help with that.
Below is my html and my middleware build in python:
middleware.py:
class TodoappMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.method == "GET":
f = open("/home/gblp250/Desktop/log", 'a')
f.write("User clicked ")
name = request.GET.get('name')
if not name == 'None':
f.write(str(name))
f.write("\n")
f.close()
elif request.method == 'POST':
f = open("/home/gblp250/Desktop/log", 'a')
f.write("User clicked ")
if request.POST.get("Login"):
nm = request.POST.get("Login")
if not nm == 'None':
f.write("Login\n")
elif request.POST.get("Authorize"):
f.write("Authorize\n")
elif request.POST.get("Assign"):
f.write("Assign\n")
elif request.POST.get("delete_task"):
f.write("Delete task\n")
elif request.POST.get("mark_complete"):
f.write("Mark as complete\n")
elif request.POST.get('authorise_users'):
form = AuthUserCheckbox(request.POST)
if form.is_valid():
ch = form.cleaned_data.get('choice')
print "User then chose "
f.write(ch)
f.close()
html:
{% extends 'todoapp/base.html' %}
{% block title %}Authorize users{% endblock %}
{% block content %}
<h2>Select users to authorize</h2>
<form method="post" action="{% url 'auth_users' %}" id="authorise_users">
{% csrf_token %}
{{ form.choice }}
<br/><input type="submit" value="Authorize" name="Authorize">
<button onclick="location.href='{%url 'dashboard' %}?name=Go back'" type="button">Go back</button>
</form>
{% endblock %}
All the request.POST.get are buttons except for authorise_users, it is a checkbox. I am not able to get the user entered value for that. All buttons clicks I have got but I am not able to get the selected value for authorise_users
Based on the error you are getting (mentioned in a comment to the question), you probably need to change the line
if request.choice.is_valid():
to
if form.choice.is_valid():
or
if form.is_valid():
Does that help to solve the error?
I have multiple form on the same page that send post request to same handler
in flask.
I am generating forms using wtforms.
what is the best way to identify which form is submitted ?
I am currently using action="?form=oneform". I think there should be some better method
to achieve the same?
The solution above have a validation bug, when one form cause a validation error, both forms display an error message. I change the order of if to solve this problem.
First, define your multiple SubmitField with different names, like this:
class Form1(Form):
name = StringField('name')
submit1 = SubmitField('submit')
class Form2(Form):
name = StringField('name')
submit2 = SubmitField('submit')
....
Then add a filter in view.py:
....
form1 = Form1()
form2 = Form2()
....
if form1.submit1.data and form1.validate(): # notice the order
....
if form2.submit2.data and form2.validate(): # notice the order
....
Now the problem was solved.
If you want to dive into it, then continue read.
Here is validate_on_submit():
def validate_on_submit(self):
"""
Checks if form has been submitted and if so runs validate. This is
a shortcut, equivalent to ``form.is_submitted() and form.validate()``
"""
return self.is_submitted() and self.validate()
And here is is_submitted():
def is_submitted():
"""Consider the form submitted if there is an active request and
the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
"""
return _is_submitted() # bool(request) and request.method in SUBMIT_METHODS
When you call form.validate_on_submit(), it check if form is submitted by the HTTP method no matter which submit button was clicked. So the little trick above is just add a filter (to check if submit has data, i.e., form1.submit1.data).
Besides, we change the order of if, so when we click one submit, it only call validate() to this form, preventing the validation error for both form.
The story isn't over yet. Here is .data:
#property
def data(self):
return dict((name, f.data) for name, f in iteritems(self._fields))
It return a dict with field name(key) and field data(value), however, our two form submit button has same name submit(key)!
When we click the first submit button(in form1), the call from form1.submit1.data return a dict like this:
temp = {'submit': True}
There is no doubt when we call if form1.submit.data:, it return True.
When we click the second submit button(in form2), the call to .data in if form1.submit.data: add a key-value in dict first, then the call from if form2.submit.data: add another key-value, in the end, the dict will like this:
temp = {'submit': False, 'submit': True}
Now we call if form1.submit.data:, it return True, even if the submit button we clicked was in form2.
That's why we need to define this two SubmitField with different names. By the way, thanks for reading(to here)!
Update
There is another way to handle multiple forms on one page. You can use multiple views to handle forms. For example:
...
#app.route('/')
def index():
register_form = RegisterForm()
login_form = LoginForm()
return render_template('index.html', register_form=register_form, login_form=login_form)
#app.route('/register', methods=['POST'])
def register():
register_form = RegisterForm()
login_form = LoginForm()
if register_form.validate_on_submit():
... # handle the register form
# render the same template to pass the error message
# or pass `form.errors` with `flash()` or `session` then redirect to /
return render_template('index.html', register_form=register_form, login_form=login_form)
#app.route('/login', methods=['POST'])
def login():
register_form = RegisterForm()
login_form = LoginForm()
if login_form.validate_on_submit():
... # handle the login form
# render the same template to pass the error message
# or pass `form.errors` with `flash()` or `session` then redirect to /
return render_template('index.html', register_form=register_form, login_form=login_form)
In the template (index.html), you need to render both forms and set the action attribute to target view:
<h1>Register</h1>
<form action="{{ url_for('register') }}" method="post">
{{ register_form.username }}
{{ register_form.password }}
{{ register_form.email }}
</form>
<h1>Login</h1>
<form action="{{ url_for('login') }}" method="post">
{{ login_form.username }}
{{ login_form.password }}
</form>
I've been using a combination of two flask snippets. The first adds a prefix to a form and then you check for the prefix with validate_on_submit(). I use also Louis Roché's template to determine what buttons are pushed in a form.
To quote Dan Jacob:
Example:
form1 = FormA(prefix="form1")
form2 = FormB(prefix="form2")
form3 = FormC(prefix="form3")
Then, add a hidden field (or just check a submit field):
if form1.validate_on_submit() and form1.submit.data:
To quote Louis Roché's:
I have in my template :
<input type="submit" name="btn" value="Save">
<input type="submit" name="btn" value="Cancel">
And to figure out which button was passed server side I have in my views.py file:
if request.form['btn'] == 'Save':
something0
else:
something1
A simple way is to have different names for different submit fields. For an
example:
forms.py:
class Login(Form):
...
login = SubmitField('Login')
class Register(Form):
...
register = SubmitField('Register')
views.py:
#main.route('/')
def index():
login_form = Login()
register_form = Register()
if login_form.validate_on_submit() and login_form.login.data:
print "Login form is submitted"
elif register_form.validate_on_submit() and register_form.register.data:
print "Register form is submitted"
...
As the other answers, I also assign a unique name for each submit button, for each form on the page.
Then, the flask web action looks like below - note the formdata and obj parameters, which help to init / preserve the form fields accordingly:
#bp.route('/do-stuff', methods=['GET', 'POST'])
def do_stuff():
result = None
form_1 = None
form_2 = None
form_3 = None
if "submit_1" in request.form:
form_1 = Form1()
result = do_1(form_1)
elif "submit_2" in request.form:
form_2 = Form2()
result = do_2(form_2)
elif "submit_3" in request.form:
form_3 = Form3()
result = do_3(form_3)
if result is not None:
return result
# Pre-populate not submitted forms with default data.
# For the submitted form, leave the fields as they were.
if form_1 is None:
form_1 = Form1(formdata=None, obj=...)
if form_2 is None:
form_2 = Form2(formdata=None, obj=...)
if form_3 is None:
form_3 = Form3(formdata=None, obj=...)
return render_template("page.html", f1=form_1, f2=form_2, f3=form_3)
def do_1(form):
if form.validate_on_submit():
flash("Success 1")
return redirect(url_for(".do-stuff"))
def do_2(form):
if form.validate_on_submit():
flash("Success 2")
return redirect(url_for(".do-stuff"))
def do_3(form):
if form.validate_on_submit():
flash("Success 3")
return redirect(url_for(".do-stuff"))
I haven't used WTForms but should work regardless. This is a very quick and simple answer; all you need to do is use different values for the submit button. You can then just do a different def based on each.
In index.html:
<div>
<form action="{{ url_for('do_stuff')}}" method="POST">
<h1>Plus</h1>
<input type = "number" id = "add_num1" name = "add_num1" required><label>Number 1</label><br>
<input type = "number" id = "add_num2" name = "add_num2" required><label>Number 2</label><br>
<input type = "submit" value = "submit_add" name = "submit" ><br>
</form>
<p>Answer: {{ add }}</p>
</div>
<div>
<form action="{{ url_for('do_stuff')}}" method="POST">
<h1>Minus</h1>
<input type = "number" id = "min_num1" name = "min_num1" required><label>Number 1</label><br>
<input type = "number" id = "min_num2" name = "min_num2" required><label>Number 2</label><br>
<input type = "submit" value = "submit_min" name = "submit"><br>
</form>
<p>Answer: {{ minus }}</p>
</div>
in app.py:
#app.route('/',methods=["POST"])
def do_stuff():
if request.method == 'POST':
add = ""
minus = ""
if request.form['submit'] == 'submit_add':
num1 = request.form['add_num1']
num2 = request.form['add_num2']
add = int(num1) + int(num2)
if request.form['submit'] == 'submit_min':
num1 = request.form['min_num1']
num2 = request.form['min_num2']
minus = int(num1) - int(num2)
return render_template('index.html', add = add, minus = minus)
Well here is a simple trick
Assume you Have
Form1, Form2, and index
Form1 <form method="post" action="{{ url_for('index',formid=1) }}">
Form2 <form method="post" action="{{ url_for('index',formid=2) }}">
Now In index
#bp.route('/index', methods=['GET', 'POST'])
def index():
formid = request.args.get('formid', 1, type=int)
if formremote.validate_on_submit() and formid== 1:
return "Form One"
if form.validate_on_submit() and formid== 2:
return "Form Two"
I normally use a hidden tag that works as an identifier.
Here is an example:
class Form1(Form):
identifier = StringField()
name = StringField('name')
submit = SubmitField('submit')
class Form2(Form):
identifier = StringField()
name = StringField('name')
submit = SubmitField('submit')
Then you can add a filter in view.py:
....
form1 = Form1()
form2 = Form2()
....
if form1.identifier.data == 'FORM1' and form1.validate_on_submit():
....
if form2.identifier.data == 'FORM2' and form2.validate_on_submit():
....
and finally in the HTML:
<form method="POST">
{{ form1.indentifier(hidden=True, value='FORM1') }}
</form>
<form method="POST">
{{ form2.indentifier(hidden=True, value='FORM2') }}
</form>
If you do it like this in the if statement it will check what was the identifier and if its equal it will run the form stuff you have in your code.
Example: Multiple WTForm in single html page
app.py
"""
Purpose Create multiple form on single html page.
Here we are having tow forms first is Employee_Info and CompanyDetails
"""
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, FloatField, validators
from wtforms.validators import InputRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisisasecret'
class EmployeeInfo(FlaskForm):
"""
EmployeeInfo class will have Name,Dept
"""
fullName = StringField('Full Name',[validators.InputRequired()])
dept = StringField('Department',[validators.InputRequired()])
class CompanyDetails(FlaskForm):
"""
CompanyDetails will have yearOfExp.
"""
yearsOfExp = IntegerField('Year of Experiece',[validators.InputRequired()])
#app.route('/', methods = ['GET','POST'] )
def index():
"""
View will render index.html page.
If form is validated then showData.html will load the employee or company data.
"""
companydetails = CompanyDetails()
employeeInfo = EmployeeInfo()
if companydetails.validate_on_submit():
return render_template('showData.html', form = companydetails)
if employeeInfo.validate_on_submit():
return render_template('showData.html', form1 = employeeInfo)
return render_template('index.html',form1 = employeeInfo, form = companydetails)
if __name__ == '__main__':
app.run(debug= True, port =8092)
templates/index.html
<html>
<head>
</head>
<body>
<h4> Company Details </h4>
<form method="POST" action="{{url_for('index')}}">
{{ form.csrf_token }}
{{ form.yearsOfExp.label }} {{ form.yearsOfExp }}
<input type="submit" value="Submit">
</form>
<hr>
<h4> Employee Form </h4>
<form method="POST" action="{{url_for('index')}}" >
{{ form1.csrf_token }}
{{ form1.fullName.label }} {{ form1.fullName }}
{{ form1.dept.label }} {{ form1.dept }}
<input type="submit" value="Submit">
</form>
</body>
</html>
showData.html
<html>
<head>
</head>
<body>
{% if form1 %}
<h2> Employee Details </h2>
{{ form1.fullName.data }}
{{ form1.dept.data }}
{% endif %}
{% if form %}
<h2> Company Details </h2>
{{ form.yearsOfExp.data }}
{% endif %}
</body>
</html>
I have been having some trouble with /quote in PSET 7 of CS50. Every time I go into the CS50 finance site, it returns:
AttributeError: 'NoneType' object has no attribute 'startswith'
I am not sure what it means, nor how to fix it. It seems to be automatically going to 'None' in the lookup function, but I am not sure why. If someone could help me, I would really appreciate it!
This is my quote part of application.py:
#app.route("/quote", methods=["GET", "POST"])
#login_required
def quote():
"""Get stock quote."""
if request.method == "POST":
symbol = request.args.get("symbol")
quote = lookup(symbol)
return render_template("quoted.html", name=quote)
else:
return render_template("quote.html")
This is my helpers.py, which is not supposed to be changed:
def lookup(symbol):
"""Look up quote for symbol."""
# reject symbol if it starts with caret
if symbol.startswith("^"):
return None
# reject symbol if it contains comma
if "," in symbol:
return None
# query Yahoo for quote
# http://stackoverflow.com/a/21351911
try:
url = "http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={}".format(symbol)
webpage = urllib.request.urlopen(url)
datareader = csv.reader(webpage.read().decode("utf-8").splitlines())
row = next(datareader)
except:
return None
# ensure stock exists
try:
price = float(row[2])
except:
return None
# return stock's name (as a str), price (as a float), and (uppercased) symbol (as a str)
return {
"name": row[1],
"price": price,
"symbol": row[0].upper()
}
Finally, this is my quote.html:
{% extends "layout.html" %}
{% block title %}
Quote
{% endblock %}
{% block main %}
<form action="{{ url_for('quote') }}" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="symbol" type="symbol"text"/>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Search for Quote</button>
</div>
</fieldset>
</form>
{% endblock %}
That error would occur when there's no "symbol" parameter in the request.
symbol = request.args.get("symbol")
quote = lookup(symbol)
Because it's not present, .get(...) will return None, and when you call lookup(None) it will try to run the following line, with symbol as None:
if symbol.startswith("^"):
Which means you're trying to do None.startswith(...), explaining the error you see.
You could check for the case where symbol is missing/None and display an error message.
symbol = request.args.get("symbol")
if symbol:
quote = lookup(symbol)
return render_template("quoted.html", name=quote)
else:
return render_template("missing_symbol.html")
Or you could just ignore it: if there's no symbol, the request is probably invalid, and you can accept that it causes an error.
I managed to find the answer, I was supposed to put:
symbol = request.form.get("symbol") instead of:
symbol = request.args.get("symbol").