#1 by manond
Dear all,
I am trying to assign treatments ('Control', 'LP', 'CMC') to my participants but it keeps on returning " KeyError: 'treatment' " when running my code. Could you help me ? Many thanks.
Here is my code:
----------------------------------------------------------------------------
class Player(BasePlayer):
...
# Assignation treatement
treatment = models.CharField(initial='', null=False)
def creating_session(self, subsession):
# List of possible treatments
treatments = ['Control', 'LP', 'CMC']
pressures = itertools.cycle(treatments)
# Assign treatments to players
if subsession.round_number == 1:
for player in self.subsession.get_players():
participant = player.participant
print(participant)
participant.treatment = random.choice(treatments)
print(participant.treatment)
# Check if treatments are balanced
participant.treatment = next(pressures)
print('Set treatment to', participant.treatment)
----------------------------------------------------------------------------
class CountingA(Page):
form_model = 'player'
form_fields = ['answerA']
timeout_seconds = 10
@staticmethod
def vars_for_template(player):
# Generate a random list of letters
letters_listA = [random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ') for _ in range(30)]
player.letters_listA = ' '.join(letters_listA) # Convert the list to a string
# Choose a random letter from the list as the target letter
target_letterA = random.choice(letters_listA)
# Count the occurrences of the target letter in the list
nb_target_letterA = letters_listA.count(target_letterA)
# Store the target letter and correct count in the model
player.target_letterA = target_letterA
player.nb_target_letterA = nb_target_letterA
return {
'letters_listA': player.letters_listA,
'target_letterA': player.target_letterA,
}
# set up payoffs based on treatments
@staticmethod
def before_next_page(player, timeout_happened):
participant = player.participant
# Record whether the participant's count is correct
player.is_correctA = (player.nb_target_letterA == player.answerA)
if participant.treatment == 'LP':
if player.is_correctA == 1:
player.total_scoreA += 1
player.taskA_payoff = Constants.taskA_correct_payoffLP
else:
player.taskA_payoff = Constants.taskA_wrong_payoffLP
else:
if player.is_correctA == 1:
player.total_scoreA += 1
player.taskA_payoff = Constants.taskA_correct_payoffC
else:
player.taskA_payoff = Constants.taskA_wrong_payoffC
----------------------------------------------------------------------------
#2 by Daniel_Frey
I see a few problems here:
- What is models.CharField? Did you define that yourself? Or do you actually want a StringField?
- Be careful with player.treatment & player.participant.treatment, those are not the same.
Where does your code generate the error? At the creating_session() function or later on the page?
#3 by Daniel_Frey
and furthermore, is creating_session() inside your Player class? This should be a function inside Subsession (for oTree 3) or in no class at all (for oTree 5)