Home > Software engineering >  Name of a dictionary is not defined accessing through console
Name of a dictionary is not defined accessing through console

Time:05-19

In my routes.py I set a variable to the converted dictionary generated from SQLAlchemy tuples right after the form validation statement.

When typing from routes import * dict(Book.query.with_entities(Book.username, Book.choice).all()) in console i get the correct dictionary as wanted {'user1': 'choice1', 'user2': 'choice2'}

If I type the name of the variable dict_of_users assiged to this dictionary I get: NameError: name 'dict_of_users' is not defined

Why it does not recognise that variable since it is in the code?

The logic behind I want to achieve:

If the user select one choice from available in the list, that user and its choice are added as key and value in the dictionary, otherwise the dictionary is empty.

My routes.py:

@app.route("/booking", methods=['POST', 'GET'])
def booking():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(seconds=5)
    form = BookingForm()
    if form.validate_on_submit():
        book = Book(username=current_user.username, choice=form.book.data)
        db.session.add(book)
        db.session.commit()
        flash('Your choice is registered', 'success')
    dict_of_users = dict(Book.query.with_entities(Book.username, Book.choice).all())
    return render_template('booking.html', title='Booking', form=form, dict_of_users=dict_of_users)

CodePudding user response:

If it's only inside of the function, you can't access it outside of the function. Since the variable is only defined in the function, you get the NameError message. A fix is to define the variable in the global scope.

EDIT:

As a response to your comment:

if you want to access the dict_of_users variable, declare it outside of the function. Then the variable will contain the value of it's latest use in the global scope, and thus accesible outside of the function.

Something like this should do the trick:

dict_of_users = None

@app.route("/booking", methods=['POST', 'GET'])
def booking():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(seconds=5)
    form = BookingForm()
    if form.validate_on_submit():
        book = Book(username=current_user.username, choice=form.book.data)
        db.session.add(book)
        db.session.commit()
        flash('Your choice is registered', 'success')
    dict_of_users = dict(Book.query.with_entities(Book.username, Book.choice).all())
    return render_template('booking.html', title='Booking', form=form, dict_of_users=dict_of_users)
  • Related