I am having errors with CS50 Finance problem in registration process - python

The error is ":( registering user succeeds" and ":( registration rejects duplicate username"
The detailed error log mentions that there is no table such as 'stock found'
Other registration processes have green ticks.
Can someone please help out with this code?
Here is my registration code in application.py
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("Oh dear, give us the username!")
# Ensure password was submitted
elif not request.form.get("password"):
return apology("You have to give us password!")
elif not request.form.get("confirmation"):
return apology("You have to confirm your password!")
# Ensure confirm password is correct
elif request.form.get("password") != request.form.get("confirmation"):
return apology("Oops, your passwords don't match up!")
# Insert user and hash of the password into the table
newuser = db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)",
username=request.form.get("username"),
hash=generate_password_hash(request.form.get("password")))
if not newuser:
return apology("Someone else swiped right on this Username, try a new one!")
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = :username",
username=request.form.get("username"))
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect(url_for("index"))
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")
I have also given below the index code below - for the error with 'stock' table
#app.route("/")
#login_required
def index():
"""Show portfolio of stocks"""
# Query infos from database
rows = db.execute("SELECT * FROM stocks WHERE user_id = :user",
user=session["user_id"])
cash = db.execute("SELECT cash FROM users WHERE id = :user",
user=session["user_id"])[0]['cash']
# pass a list of lists to the template page, template is going to iterate it to extract the data into a table
total = cash
stocks = []
for index, row in enumerate(rows):
stock_info = lookup(row['symbol'])
# create a list with all the info about the stock and append it to a list of every stock owned by the user
stocks.append(list((stock_info['symbol'], stock_info['name'], row['amount'], stock_info['price'], round(stock_info['price'] * row['amount'], 2))))
total += stocks[index][4]
return render_template("index.html", stocks=stocks, cash=round(cash, 2), total=round(total, 2))
HTML for register
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{% block main %}
<form action="/register" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmation" placeholder="Confirm password" type="password">
</div>
<button class="btn btn-primary" type="submit">Register</button>
</fieldset>
</form>
{% endblock %}
HTML for Index
{% extends "layout.html" %}
{% block title %}
Stocks
{% endblock %}
{% block main %}
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">Symbol</th>
<th scope="col">Name</th>
<th scope="col">Shares</th>
<th scope="col">Price</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
{% for stock in stocks %}
<tr>
<th scope="row">{{ stock[0] }}</th>
<td>{{ stock[1] }}</td>
<td>{{ stock[2] }}</td>
<td>{{ stock[3] }}</td>
<td>{{ stock[4] }}</td>
</tr>
{% endfor %}
<tr>
<th scope="row">Cash</th>
<td></td>
<td></td>
<td></td>
<td>{{ cash }}</td>
</tr>
<tr>
<th scope="row"></th>
<td></td>
<td></td>
<td></td>
<td>{{ total }}</td>
</tr>
</tbody>
</table>
{% endblock %}

Before Insert user and hash of the password into the table, do SELECT on the request.form.get("username"), to see if the username already exists. Then if something is returned, return an error message. I think that should solve the problem.

Related

Django: select all data from a row in a html table and use them in a view

I am new to both django and web development.
The task is to run a script when pressin a button using the data contained in the specific row of an html table.
So if i clik on the second button "Run script" it uses all the data in that row (8888, 2020/06/21 06:00) in a separate script to performe some task.
Currently my html file looks like this:
There are 2 sections one for uplading the information that goes in the table one the table which displays them
<h1>Approach Path KML Generator</h1>
<h2>Generate the KML file here:</h2> <form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button onclick="location.href='{% url 'approach_path_receptorsKML:Proejct Creator' %}'">Upload</button> </form>
<h2>Projects Available:</h2>
<table class="table">
<thead>
<tr>
<th>Project ID</th>
<th>Date KML</th>
<th>Time KML</th>
<th>Date-Time Uploaded</th>
<th>Run The Conversion</th>
<th>KML File</th>
</tr>
</thead>
<tbody>
{% for project in latest_project_list %}
<tr>
<td>{{ project.project_ID }}</td>
<td>{{ project.date_kml }}</td>
<td>{{ project.time_kml }}</td>
<td>{{ project.upload_time }}</td>
<td>
<button method="post" value="collect data" name="{{ project.project_ID }}|{{ project.date_kml }}|{{ project.time_kml }}|{{ project.upload_time }}">Run script</button>
</td>
<td>
Download KML File
</td>
</tr>
{% endfor %}
</tbody> </table>
And this is the view I have created:
def ProjectCreator(request):
form = DocumentForm()
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid:
form.save()
elif 'collect data' in request.POST.values():
values = [key for key in request.POST.keys()]
print(values)
else:form = DocumentForm()
I have tried to use this guide (How do I pass table data from a template over to Django on a button/submit click?) however, I have been insuccesfull.
If anyone can spot the mistake I have made and give me some explanation I would be grateful.
Thanks
It doesn't work because you have incorrect HTML layout. Button itself doesn't do anything - in order to send POST request, it should be in <form> tag. Try following:
{% for project in latest_project_list %}
<tr>
<td>{{ project.project_ID }}</td>
<td>{{ project.date_kml }}</td>
<td>{{ project.time_kml }}</td>
<td>{{ project.upload_time }}</td>
<td>
<form method="post">
{% csrf_token %}
<button value="collect data"
name="{{ project.project_ID }}|{{ project.date_kml }}|{{ project.time_kml }}|{{ project.upload_time }}">
Run script
</button>
</form>
</td>
<td>
Download KML File
</td>
</tr>
{% endfor %}
This will work, but I doubt this is great way of achieving this. You can just send project.pk with POST request and fetch project in view. This way you can be sure user will not send incorrect/malicious data with request. It is especially important since your code will run script based on data.

Pass information from html form to python flask

I am new to flask and web applications, trying to create a web application that takes the name and the sport for each user and store it in sqlite DB, now Iam trying to remove users from the DB by taking the registrant id from the html to flask.
flask:
#app.route("/deregister")
def deregister():
value_from_html = ?????
db.excute("DELETE * FROM registrant WHERE id = ?", value_from_html)
html:
{% extends "layout.html" %}
{% block body %}
<h1>Registrant name</h1>
<tbody>
{% for registrant in registrants %}
<tr>
<td>{{ registrant.name }}</td>
<td>{{ registrant.sport }}</td>
<td>
<form action="/deregister" method="post">
<input name="id" type="hidden" value="{{ registrant.id }}"> !-- trying to pass registrant.id to flask --!
<input type="submit" value="Deregister">
</form>
</td>
</tr>
{% endfor %}
</tbody>
{% endblock %}
python code is not complete yet.
You can recieve the form data in the following way.
#app.route("/deregister", methods=['POST'])
#login_required
def deregister():
try:
if request.method == 'POST':
if request.files:
uploaded_file = request.files['filename']
data = uploaded_file.stream.read()
In order to send a variable to flask, you dont need to use forms, you can easily do that in the following way,
#app.route("/deregister/<string:id>", methods=['POST'])
#login_required
def deregister(id):
try:
variable = id
print(variable)
In html, keep this,
{% extends "layout.html" %}
{% block body %}
<h1>Registrant name</h1>
<tbody>
{% for registrant in registrants %}
<tr>
<td>{{ registrant.name }}</td>
<td>{{ registrant.sport }}</td>
<td>
<a href='/deregister/{{ registration.id }}'>Send Id</a>
</td>
</tr>
{% endfor %}
</tbody>
{% endblock %}
After trying to solve it my self finaly Ive found a way to do that:
1)Add button in my html to remove from DB:
I hope that this will help any one as it did for me.

Python Django tables with checkbox delete option

I am new to Django and currently trying to display a table with a checkbox which displays the list of records from the database and would have a delete button to delete multiple records using checkbox.
How to display a table with checkbox and delete button?
Appreciate your help!
Here is my code related to it:
models.py
class Customer(TimeStamp):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100,blank=True,help_text="Long-form name (optional)")
comments = models.TextField(blank=True)
class Meta:
ordering = ['-id']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('App_CUS:customer_list')
views.py
class CustomerListView(ListView):
queryset = Customer.objects.order_by('id')
model = Customer
paginate_by = 10
context_object_name = 'customers'
template_name = 'App_CUS/customer_list.html'
customer_list.html
customer_list.html:
{% extends 'index.html' %}
{% load buttons %}
{% block content %}
<div class="pull-right">
{% if perms.App_CUS.customer_add %}
{% add_button 'App_CUS:customer_add' %}
{% delete_button 'App_CUS:customer_delete' %}
{% endif %}
</div>
<h1>{% block title %}Customers{% endblock %}</h1>
<div class="col-md-9">
<div class="table-responsive">
<table class="table table-hover table-headings table-bordered">
<thead>
<tr>
<th class="pk">
<input class="toggle" title="Toggle all" type="checkbox">
</th>
<th>ID</th>
<th>Customer Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<th class="pk">
<input class="toggle" title="Toggle all" type="checkbox">
</th>
<td>{{ customer.pk }}</td>
<td>{{ customer.name }}</td>
<td>{{ customer.description }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
I would add to your existing
{% for customer in customers %}
a new td tag including something like:
<td>
<div class="checkbox">
<input type="checkbox" name="name_check_{{customer.name}}" id="id_check{{customer.name}}" value="1"
{%if customer.data == 0 %}unchecked {%else%} checked {%endif%}>
</div>
<td>
I've used customer.data to represent a value stored in your db.
You could then write some js to do something on click of each new checkbox.
<script>
$(document).ready(function() {
$("#id_check_{{customer.id}}").on("click", function(){
#do something / ajax call etc..
OR
pass these values back to the view on form post (we've named each checkbox unique to the customer), then process the deletions from there.

Flask Form Only Passing First Item

I am building a cart using Flask for learning purposes. I chose to use SQLite with peewee(ORM) and WTForms. I have it set to display the items from the db with a description and image. I have a form that asks for the quantity then it should add the item and its quantity to the side bar.
The Issue
When You enter a quantity and hit 'add' all the quantity fields will fill with that number and it will post the name of the first item from the database to the sidebar with that quantity.
app.py
#app.route('/cart', methods=['GET', 'POST'])
#login_required
def cart():
form = forms.PartsSelectForm()
if request.method == 'POST':
l_name = Parts.get(Parts.id).part_name
models.List.create(l_part_name=l_name,
l_part_qty=form.quantity.data)
parts = Parts.select()
list = List.select()
return render_template('cart.html', parts=parts, list=list, form=form)
forms.py
class PartsSelectForm(Form):
quantity = IntegerField()
cart.html
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Image</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
{% for part in parts %}
<tr>
<td>{{ part.part_name }}</td>
<td>{{ part.part_desc }}</td>
<td style="width: 200px; height:200px;"><img src="/static/img/{{ part.part_img }}" style="max-height:100%; max-width:100%"></td>
<form method="POST" action="">
<td>{{ form.quantity }}</td>
<td><button type="submit" id="submit" class="btn btn-success">Add</button></td>
</form>
</tr>
{% endfor %}
</table>
You loop over your parts, but you always use form.quantity, which will be the same on every iteration idependently from which "part" you're currently looping over.

Django PasswordInput is printing object instead of form field

I am trying to create my own authentication system by making use of Django Auth module. The problem is when I print my form in the template, Username and text field is displaying fine but the password field its displaying object something like this <django.forms.widgets.PasswordInput object at 0x00000000039E1710>
Here is my form
class UserLoginForm(forms.Form):
username = forms.CharField(required = True)
password = forms.PasswordInput(render_value = True)
And the template goes here.
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="/portal/login">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
Some one help me on this
-Vikram
change
password = forms.PasswordInput(render_value = True)
to
password = forms.CharField(widget=forms.PasswordInput(render_value = True))
OK, I got the answer: After correcting the form like this its displaying fine
class UserLoginForm(forms.Form):
username = forms.CharField(required = True)
password = forms.CharField(widget=forms.PasswordInput())
Sorry for the spam
-Vikram

Categories