Displaying 0 instead of None in my app

42 views
Skip to first unread message

Joe

unread,
Jul 24, 2015, 7:24:13 AM7/24/15
to web2py-users
I want to display 0 instead of None for the session.counter or session.wrong_counter in my app. I have tried about 10 different ways to do this but I am not getting it right for some reason.

This is the Controller for the page score:

    def score():
        image = db.pic(request.args(0,cast=int)) or redirect(URL('index'))
        correct = image.id == session.pic_id
        next_game = random.randint(1, 35)
        wrong_counter = []
        right_counter = []
        if correct:
            session.counter = (session.counter or 0)+1
            right_counter=session.counter
        if not correct:
            session.wrong_counter = (session.wrong_counter or 0)+1
            wrong_counter=session.wrong_counter
        return locals()

In the View I have {{=session.counter}} and {{=session.wrong_counter}}. When the page score first visited during the session one of them will display 1 and the other will display None depending on the correct or not correct conditions as expected, however, I want to display 0 instead of None.

I would very much appreciate some help with this.


Alex

unread,
Jul 24, 2015, 8:48:51 AM7/24/15
to web2py-users
that's because the other session variable is not initialized. try this for example:
if correct:
session.counter = (session.counter or 0)+1
session.wrong_counter = session.wrong_counter or 0
right_counter=session.counter
else:
session.wrong_counter = (session.wrong_counter or 0)+1
session.counter = session.counter or 0
wrong_counter=session.wrong_counter

Alex

Anthony

unread,
Jul 24, 2015, 8:51:33 AM7/24/15
to web...@googlegroups.com, degrou...@gmail.com
Well, the code checks two conditions, correct and not correct, and only one of those is true on any given request. Yet you only set the value of one of your session variables within each condition -- so of course the one you don't set is None (it is actually undefined, but the session object is a Storage object, which returns None for any requested attribute that doesn't exist). Outside of the conditional logic, you could do something like:

session.counter = 0 if session.counter is None else session.counter

Alternatively, you could move that to the view:

{{=0 if session.counter is None else session.counter)}}

Anthony

Joe

unread,
Jul 27, 2015, 2:25:26 AM7/27/15
to web2py-users, mrau...@gmail.com
Thanks very much Alex, this works as well, I appreciate it. I ended up changing the code in the View as per Anthony's suggestion like so: {{=0 if session.counter is None else session.counter)}}

Joe

unread,
Jul 27, 2015, 2:30:25 AM7/27/15
to web2py-users, abas...@gmail.com
Thanks Anthony, I changed the  View as per your answer. This was the easiest solution. It works great, I appreciate it. (you forgot to take out one of the parenthesis at the end but I removed it)
Reply all
Reply to author
Forward
0 new messages