cs50 week 9 finance. I get the error that loggining in as registered user does not succeed - cs50

when i ruck check50 i get the error
when i log in as a registered account I also do not get any errors
:( logging in as registered user succceeds
Cause
expected status code 200, but got 400
Log
sending POST request to /login
checking that status code 200 is returned...
however when i use the program myself the logging in as a registered user works fine
this is my register code from application.py
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
if (request.method == "POST"):
username=request.form.get('username')
password=request.form.get('password')
confirmation=request.form.get('confirmation')
if not username: #if there is no username
return apology('enter a username')
elif not password: #if there is no password
return apology('enter a password')
elif not confirmation: #if there is no confirmation
return apology('Password confirmation is required!')
if password !=confirmation: #if password is not equal to confirmation
return apology("Password does not match")
hash = generate_password_hash(password)
try:
db.execute("INSERT INTO users (username,hash) VALUES (?, ?)", username, hash)
return redirect('/')
except:
return apology("Username has allready been registered")
else:
return render_template("register.html") #display the page if no errors
this is also my template register.html code for the code above
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{% block main %}
<form action="/register" method="post">
<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>
</form>
{% endblock %}

you have to have the index.html (the table) made for that check50 to mark is correct

Not an exact answer, but you can try this workaround.
Instead of using try and except blocks, get the rows from the database having username as the username entered by user. Then check if there are no rows. If there are no rows then you can assume the username is unique and proceed.

I am late but this answer is for those who are also facing similar issue.
In my case the issue was in index page it happens when you login for the first time there is nothing to show so for that I had returned apology saying "you don't have any stocks" and apology was sending 400 error code so I just removed that code and the problem solved.
this line is simply telling that when a new user login you app is showing 400 error.

Related

Flask Jinja User Checkbox List of Items

I'm stumped at the moment on what to do here. I have a Flask server where an app.route has a list called "addresses" that gets passed to rendered page customeraddresses.html to be displayed.
The goal is to show the user the list displayed by checkboxes so they can check the ones they would like to remove from the list. Currently I'm displaying a list of checkboxed items for the user to check, but I'm not sure how to grab everything that the user wants to remove.
How can I pass everything to app.route /removelistitems that the user checked?
Any assistance would be greatly appreciated.
app.py
from flask import Flask, render_template, request
import requests
import json
app = Flask(__name__)
...
...
#app.route('/customeraddresses', methods=["POST"])
def currentaddresses():
customername = request.form.get("customername")
addresses = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']
return render_template("/customeraddresses.html", customername=customername, addresses=addresses)
#app.route('/removelistitems', methods=["POST"])
def removeitems():
thingstoremove= request.form.get('thingstoremove')
currentaddresses.html
...
...
<form action="/removelistitems" method="POST">
<div class="row">
<div class="col">
</div>
<div class="col-md-11">
{% for address in addresses %}
<div class="form-group">
<label for="existing_{{address}}" class="control-label col-sm-2">{{address}}</label>
<input type="checkbox" name="existing_{{address}}"/>
<br/>
</div>
{% endfor %}
<button type="submit" [disabled]="!name" class="btn btn-secondary">Submit</button>
</div>
<div class="col">
</div>
</div>
</form>
...
...

Python Error AttributeError: 'NoneType' object has no attribute 'encode'

Im creating an update password function on a project using python and flask. The users can update their password by inserting their current password into the first input field in the form and their new password into the second field. The problem is that once I click the update button, I keep getting the error in the title above. AttributeError: 'NoneType' object has no attribute 'encode'
I have inserted the python code I am using below
#user.route("/update_password/<username>", methods=['GET', 'POST'])
def update_password(username):
user = mongo.db.users.find_one({"username": username})
if request.method == "GET":
return render_template(
"update_password.html", username=username)
if request.method == 'POST':
updated_password = generate_password_hash(
request.form.get('updated-password'))
if check_password_hash(
user['password'], request.form.get('existing-password')
):
mongo.db.users.update_one(
{'username': username},
{'$set': {'password': updated_password}}
)
flash("Password Updated Successfully")
return redirect(url_for("user.profile", username=user['session']))
else:
flash("Passwords Do Not Match")
return redirect(url_for("user.update_password", username=user['session']))
Here's the html code I am using for the form:
<div class="row">
<div class="col-lg-8 col-md-10 offset-lg-2 offset-md-1">
<div class="card">
<div class="card-body text-center">
<h1>Update Password</h1>
<form method="POST" action="{{ url_for('user.update_password', username=username) }}">
<div class="mb-3">
<i class="fas fa-lock icon-style"></i>
<label for="existing-password" class="form-label">Enter your existing password</label>
<input type="password" name="existing-password" class="form-control" id="existing-password" required>
</div>
<!-- Password pattern from w3 Schools. See contribution in ReadMe -->
<div class="mb-3">
<i class="fas fa-lock icon-style"></i>
<label for="updated_password" class="form-label">Enter your new password</label>
<input type="password" name="updated_password" class="form-control" id="updated_password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}"
title="Must contain at least one number, one uppercase and lowercase
letter, and at least 8 or more characters" required>
</div>
<button type="submit" class="btn btn-lg register-btn">Update</button>
</form>
</div>
</div>
</div>
</div>
When inspecting the code, it seems there may be a problem with my python function on the following line
updated_password = generate_password_hash(request.form.get('updated-password'))
I would be so grateful if anybody could give me any information on how to solve this
I assume the error is because of field name mismatch. In the Form
<input type="password" name="updated_password">
name is updated_password
And in your route:
if request.method == 'POST':
updated_password = generate_password_hash(
request.form.get('updated-password'))
you are accessing
updated-password
which will give you None because the key name is wrong

Form data display on terminal & doesn't save in postgres database django

In my cause of learning django, I decided to start with small projects, I'm working on a simple registration page. I have my form on the home page (index.html). And I have a view.py page I pass all the data from the form to my postgres db. I realise data does not save in db, instead all the registration data display in terminal and the url bar. Here's my code;
Form (index.html)
<form action="/index/" method="POST">
{% csrf_token %}
<div><p><label for="fName">First Name</label></div>
<div><input type="text" name="fName"></input></div>
</p>
<p>
<label for="lName">Last Name</label>
<input type="text" name="lName"></input>
</p>
<p>
<label for="email">Email</label>
<input type="text" name="email"></input>
</p>
<div><p><label for="uName">Username</label></div>
<div><input type="text" name="uName"></input></div>
</p>
<p>
<label for="password1">Password</label>
<input type="password" name="Password1"></input>
</p>
<p>
<label for="password2">Confirm Password</label>
<input type="password" name="Password2"></input>
</p>
<div> <p><input type="submit"></input></p> </div>
</form>
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
def index(request):
if request.method == 'POST':
first_name = request.POST['fName']
last_name = request.POST['lName']
username = request.POST['uName']
password1 = request.POST['password1']
password2 = request.POST['password2']
email = request.POST['email']
user = User.objects.create_user(username=username, password=password1, email=email,
first_name=first_name, last_name=last_name)
user.save()
print('user created')
return redirect('/')
else:
return render(request, 'index.html')
Database setting on settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bookconf',
'USER': 'postgres',
'PASSWORD': 'olumide',
'HOST': 'localhost',
'PORT': '5432',
}
}
I suspect the data is collected and them skip to executed this return render(request, 'index.html') because after I enter submit, the home page(index.html) gets reloaded.
In addition, I'm certain psycopg2 is installed. No data gets saved in the db and no error messages except the message below.
Message on terminal
[03/Sep/2020 04:22:18] "GET / HTTP/1.1" 200 25753
[03/Sep/2020 04:22:37] "GET /?csrfmiddlewaretoken=LtMIZL5z9yGYElCkunBrkMt2mS7rMr90cyxlHPVUfiA6hpaF80Phfpjbrp6RUVpj&fName=Ken&lName=Cole&email=kcole%40mail.com&uName=k.cole&Password1=1122&Password2=1122 HTTP/1.1" 200 25753
Ideas on how to fix this will be much appreciated. Thanks

Django - Form is not saving to Db

I'm using for authentication extended AbstractUser and ModelForm. When I write on HTML page only {{ form }} everything works fine, the form is submitting, but in the following case I've added some stylings, but now nothing works. Please, help me find the reason.
HTML:
<form method='POST'>
{% csrf_token %}
<div class="sign-up-user">
<div class="sign-up-user-container">
<div class="sign-up-user-left">
<label for="">{{form.username.label}}</label>
{{form.username}}<br>
<label for="">{{form.password.label}}</label>
{{form.password}}<br>
<label for="">{{form.branch.label}}</label><br>
{{form.branch}}<br>
<label for="">{{form.license_number.label}}</label>
{{form.license_number}}<br>
<label for="">{{form.fin_number.label}}</label>
{{form.fin_number}}<br>
<label for="">{{form.voen_number.label}}</label>
{{form.voen_number}}<br>
</div>
</div>
<input type="submit" value="Register User" class="sign-up-btn">
</div>
</form>
Include two lines to your HTML to understand whats going wrong:
{{ form.errors }}
{{ form.non_field_errors }}
This will display any errors that are associated with the form. If they dont then in your views do the following:
form = YourForm()
if form.is_valid():
// Do things
else:
print (form.errors)
print(form.non_field_errors)
This will display some other errors that you are missing.

Submitting a HTML form in Flask creates error with request.form

Hey I am new to Flask and am trying to make a basic quiz app,
#app.route('/answers', methods=['GET', 'POST'])
def answers():
correct = 0
incorrect = 0
total = correct + incorrect
if request.method == 'POST':
submitted_answer = request.form['answer']
if submitted_answer == question_option1:
correct += 1
new_result = Question(correct=correct, total=total)
db.session.add(new_result)
db.session.commit()
else:
incorrect += 1
new_result = Question(incorrect=incorrect, total=total)
db.session.add(new_result)
db.session.commit()
return redirect('/answers')
all_questions = Question.query.order_by().all()
return render_template('answers.html', questions=all_questions, correct=correct, incorrect=incorrect, total=total)
while the html code looks like this
{% extends 'base.html' %}
{% block body %}
<p1>
<list>
{% for question in questions %}
<h2>{{ question.text }}</h2>
<input type="radio" name="answer" value="option1"> {{ question.option1 }} <br>
<input type="radio" name="answer" value="option2"> {{ question.option2 }} <br>
<input type="radio" name="answer" value="option3"> {{ question.option3 }} <br>
<input type="radio" name="answer" value="option4"> {{ question.option4 }} <br>
{% endfor %}
</list>
<form action='/answers' method='POST'>
<input type="submit" name="submitted" value="Check Scores">
</form>
<p1>You got a score of {{ correct }}/{{ total }}</p1>
</p1>
{% endblock %}
In a different part of my app I am able to get information from the HTML using the same method but in this case I keep getting the error
'werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'answer''
when I try to submit the checklist and can't work out why
I am new to programming so sorry if i'm missing something very basic but thanks for the help!
Your answer inputs need to be inside the form tag to be submitted - there is no 'answer' element in the form you are submitting

Resources