0

I am stuck on the final section of PSET8 finance, /check. It seems that the data for "username" is not being passed from the web page to the python script. The value for "username" in the python script is coming back as None.

My javascript source is as follows:

var username = document.getElementById("username");
    var inputForm = document.getElementById("form");

    document.getElementById("submit").addEventListener("click", function(event) {
                 event.preventDefault()
    });

    inputForm.onclick = function(data) {
        $.get("/check?username=" + username.value, function() {
            alert("CHECKING")
            if (data == false) {
                inputForm.submit();
            }
            else {
                alert("Sorry - that username is taken!");
            }
        });
    };

and the corresponding /check in python is:

@app.route("/check", methods=["GET"])
def check():
"""Return true if username available, else false, in JSON format"""

print("***RUNNING CHECK***")
# get username from web form
username = request.form.get("username")
print(username)

# check that username is longer than 1, then pull list from DB to check against
if len(username) > 1:
    usernames = db.execute("SELECT username FROM users")

# return false if username is available
if username in usernames:
    return jsonify(False)

# return true if username is NOT available
else:
    return jsonify(True)

The error is as follows:

TypeError: object of type 'NoneType' has no len()

But I can see it getting passed as per the below:

TypeError: object of type 'NoneType' has no len()

Any help/thoughts are appreciated, thank you!

2 Answers 2

2

So, as it turns out - the error was in the Python code. I used "request.form.get()" when I should have used "request.args.get()" since its a GET request not a POST request. Using "request.args.get()" fixed it and it is now working as expected. Thank you @Blauelf!

1

I don't think the "click" event of the form should be used, but the "submit" event. And I would do the preventDefault and the GET request in one callback function.

In theory, you should use "/check?username=" + encodeURIComponent(username.value), or use jQuery's features by "/check", {username: username.value}, which encodes the value automatically. Is relevant if you enter special characters in the user name field, like & or %.

Also, check again when to return jsonified True or False.

I'd do if username: instead of if len(username):, or maybe if username != None and len(username) >= 1:, that should prevent the error. Still no idea why it would show up at all.

This username in usernames does not work, since usernames contains a list of dicts. An expression username in [elem["username"] for elem in usernames] might work, but I would prefer a WHERE directly in the SQL statement.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .