oTree Forum >

How do I save a variable from a live method as a global variable to access it on every page that follows?

#1 by Hussein

Could someone tell me how I can save the userInput? I am frustrated and really need help because my deadline is in a few days. I would really appreciate if someone could help me.

This is the relevant code:

__init__.py

import json
from otree.api import *

doc = """
Your app description
"""


class C(BaseConstants):
    NAME_IN_URL = 'corporate_decision_making'
    PLAYERS_PER_GROUP = 50
    NUM_ROUNDS = 1
    payment_per_correct_answer = cu(0.1)


class Subsession(BaseSubsession):
    def creating_session(self):
        group_size = int(self.session.num_participants / 3)
        group_matrix = self.get_group_matrix()
        for group in group_matrix:
            players = group.get_players()
            for p in players:
                p.group = group.id


class Group(BaseGroup):
    def set_payoffs(self):
        for player in self.get_players():
            player.payoff = C.payment_per_correct_answer


class Player(BasePlayer):
    pass
    
class Message(ExtraModel):
    group = models.Link(Group)
    sender = models.Link(Player)
    text = models.StringField()


def to_dict(msg: Message):
    return dict(sender=msg.sender.id_in_group, text=msg.text)


# PAGES

class PT1(Page):
    def is_displayed(self):
        return self.id_in_group == 1

    @staticmethod
    def js_vars(player: Player):
        return dict(my_id=player.id_in_group)

    @staticmethod
    def live_method(player: Player, data):
        my_id = player.id_in_group
        group = player.group
        print('received', player.id_in_group, ':', data)

        if 'userInput' in data:
            user_input = data['userInput']
            player.participant.vars['userInput'] = user_input

        return {my_id: [to_dict(msg) for msg in Message.filter(group=group)]}


class DoRR(Page):
    pass
    
page_sequence = [PT1, DoRR]

The relevant Javascript snippet from PT1.html where I get the userInput:
if (Number(userInput) === correctValue || Number(userInput) > correctValue || Number(userInput) < correctValue) {
    liveSend(userInput)
    conversationState = "getting_name";
    txtInput.disabled = true;
    nextButton.removeAttribute("disabled");
    return "Alright, I reported the value.";
}

And the DoRR.html where i want to display the received data i got from the livemethod in PT1:
{{ block title }}
    DoRR
{{ endblock }}


{{ block content }}

    <p>This is your number: {{ player.user_input }}</p>


    {{ formfields }}
    {{ next_button }}

{{ endblock }}

#2 by Daniel_Frey

Does your live-method work correctly and does the input get stored in player.participant.vars['userInput']?

If yes, I think you just need to replace {{ player.user_input }} with  {{ participant.vars.userInput }}

Write a reply

Set forum username