Forums

Flask: issue with dictionary - TypeError: 'builtin_function_or_method' object is not iterable

I am trying to teach myself Flask and I have set up this test where I ask the user to input a number, do some checks on the number and then insert it to a dictionary. I then want to print out the dictionary to ensure that it worked, but I keep getting errors. I have tried a lot of different setups and am about to give up by now. Right now the error in the error logs says the following:

File "/home/majaokholm/mysite/templates/test2.html", line 10, in <module> {% for key, value in theBoard.items %} TypeError: 'builtin_function_or_method' object is not iterable

but previously I have also gotte this error:

File "/home/majaokholm/mysite/flask_app.py", line 20, in test elif theBoard[move] != ' ': NameError: name 'theBoard' is not defined

My app.py code: import json from flask import Flask, url_for, render_template, make_response, redirect, request

app = Flask(__name__)
app.config["DEBUG"] = True

theBoard = {1:' ', 2:' ', 3:' ', 4: ' ', 5:' ', 6: ' ', 7:' ', 8:' ', 9:' '}

@app.route('/test', methods=["GET", "POST"])
def test():
if request.method == 'POST':
    x = request.form['move']
    move = int(x)
    valid_moves = [1,2,3,4,5,6,7,8,9]
    if move not in valid_moves:
        return 'you did not specify a valid move, please try again!'
    elif theBoard[move] != ' ':
        return 'you can not play that space, it is taken'
    else:
        theBoard[move] = 'X'
        return render_template("test2.html", theBoard=theBoard)

return render_template("test.html")

My test2 html template: <!DOCTYPE html> <html> <head> <title>Test2</title> </head>

<body>
<table>

{% for key, value in theBoard.items %}
<h2>Key: {{key}}</h2>
<h2>Value: {{value}}</h2>
{% endfor %}

</table>

</body>
</html>

And finally my test.html code: <!DOCTYPE html> <html> <head> <title>Test</title> </head>

<body>

<div class="enter name">
<form action="{{ url_for('test') }}" method="POST">
    <lable>Please specify your move (1,2,3,4,5,6,7,8,9)</lable>
    <input type="number" name="move" value"">
    <input type="submit" value="Make you move!">
</form>
</div>


</body>
</html>

Any help would be greatly appreciated! Thank you!

I found my error, it is in the test2.html file, and should be: {% for key, value in theBoard.items() %} and not {% for key, value in theBoard.items %}