Skip to content
Advertisement

CS50(2021) – Finance. :( registration rejects duplicate username – expected status code 200, but got 400

I´m new to programming, doing CS50 and currently struggling to complete the Pset9 – Finance, version from 2021. I´ve read as many threads I could find about the same issue, but none of the answers helped me to solve the problem yet.

Application.py is doing what the problem briefing required, and I passed all tests except for this one, check50 is expecting a status code 200 but I send a 400.

Check50 failed

Something to keep in mind:

  • Registration works as expected. I am able to register new users, and when the same username tries to register I show a 400 error.
  • Index function is completed, and fully functional showing all required data.
  • No script in Register.html to check username when pressing the submit button. I have been unable to write the right script. Not sure if this is something CS50 is expecting after all, but happy to hear anyone who has passed this test.

I would really appreciate it if someone can take a look at the code below, and let me know if I am doing something wrong or just point me in the right direction. Thanks in advance!

Here is my code for register in application.py :

@app.route("/register", methods=["GET", "POST"])
def register():

    # Forget any user_id
    session.clear()

    # Registering a user when POST method
    if request.method == "POST":

        # Capturing name and password
        name = request.form.get("username")
        key1 = request.form.get("password")
        key2 = request.form.get("confirmation")

        # If fields are empty render apology
        if not name:
            return apology("Sorry, name is empty", 400)

        elif not key1 or not key2:
            return apology("Sorry, password is empty", 400)

        # If keys are different render an apology
        elif key1 != key2:
            return apology("Sorry, passwords do not match", 400)

        # Once password is valid then hash it before storing it.
        key = generate_password_hash(key1, method='pbkdf2:sha256', salt_length=8)

        # Checking if username exists in the database
        raws = db.execute("SELECT * FROM users WHERE username = :name", name=name)
        if len(raws) == 1:
            return apology("Sorry, username already exists", 400)

        # Include register into our database
        db.execute("INSERT INTO users (username, hash) VALUES(?, ?)", name, key)

        # Query again the user row, so we can pass into a session
        rows = db.execute("SELECT * FROM users WHERE username = :name", name=name)

        # Login the user just registered
        session["user_id"] = rows[0]["id"]

        # return render_template("register.html")
        return redirect("/")

    else:
        return render_template("register.html")

Here is index in application.py :

@app.route("/")
@login_required
def index():

    """Show portfolio of stocks"""
    # Query stock information from user session
    stocks = db.execute("SELECT stock_symbol, stock_name, shares, value, price FROM (SELECT stock_symbol, stock_name, SUM(shares) as shares, SUM(value) as value, price FROM stocks WHERE user_id=:session GROUP by stock_symbol) WHERE shares>0", session=session["user_id"])

    # Loop to sum up all stock value up
    stockValue = 0
    for stock in stocks:
        stockValue += stock["value"]

    # Query cash information from user session and send this to the html
    row_cash = db.execute("SELECT cash FROM users WHERE id=:session", session=session["user_id"])
    cash = row_cash[0]["cash"]

    # Grand total variable adding up stock value and cash
    grand_total = stockValue + cash

    return render_template("index.html", stocks=stocks, cash=usd(cash), grand_total=usd(grand_total))

Here is Register.html:

{% 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="Repeat Password" type="password">
        </div>
        <button class="btn btn-primary" type="submit">Register</button>
    </form>

{% endblock %}

And here is index.html:

{% extends "layout.html" %}
    
    {% block title %}
        Stocks
    {% endblock %}

{% block main %}


            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Symbol</th>
                        <th>Name</th>
                        <th>Shares</th>
                        <th>Price</th>
                        <th>Grand Total</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Loop through the database entries to display them in this table -->

                    {% for stock in stocks %}
                        <tr>
                            <td>{{ stock.stock_symbol }}</td>
                            <td>{{ stock.stock_name }}</td>
                            <td>{{ stock.shares }}</td>
                            <td>{{ stock.price | usd }}</td>
                            <td>{{ (stock.value) | usd }}</td>
                        </tr>
                    {% endfor %}

                </tbody>
                <tfoot>
                    <tr>
                        <td>Overall stock value</td>
                        <td colspan=3></td>
                        <td>{{ "${:,.2f}".format(stocks|sum('value')) }}</td>
                    </tr>
                    <tr>
                        <td>CASH</td>
                        <td colspan=3></td>
                        <td>{{ cash }}</td>
                    </tr>
                    <tr>
                        <td colspan=4></td>
                        <td>{{ grand_total }}</td>
                    </tr>
                </tfoot>
            </table>


{% endblock %}

Advertisement

Answer

The issue was finally fixed when I deleted all my data in users.db thencheck50 passed it correctly. It seems that data was causing the whole problem, and once deleted everything got fixed.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement