#1 by Riley
Hello,
this may be a simple question but I am just starting out with otree and I have been working on this problem for multiple days and I am not making any progress.
So I want to randomize all participants into two groups (control and treatment) and then I want to have it displayed on the first page group to what group they belong and were randomized in.
However, I always get this error:
TypeError: player.treatment_group is None. Accessing a null field is generally considered an error. Or, if this is intentional, use field_maybe_none()
File randomization/Welcome.html, line 7, in player.treatment_group
4.
5. {{ block content }}
6.
7. <p>You have been randomly assigned to group: <strong>{{ player.treatment_group }}</strong></p>
8.
9.
10. {{ next_button }}
I tried so many different ways but I either get this error or something like "player is not an attribute of Player" or something like this. I hope you can help me to get this simple thing programmed and explain where my mistake is. Below you'll find my code. Thank you so much.
Here is my init.py:
from otree.api import *
import random
class Constants(BaseConstants):
name_in_url = 'random_groups'
players_per_group = None
num_rounds = 1
class Subsession(BaseSubsession):
def creating_session(self):
for player in self.get_players():
player.treatment_group = random.choice(['A', 'B'])
class Group(BaseGroup):
pass
class Player(BasePlayer):
treatment_group = models.StringField()
# Pages
class Welcome(Page):
pass
page_sequence = [Welcome]
Here is my html:
{{ block title }}
Welcome
{{ endblock }}
{{ block content }}
<p>You have been randomly assigned to group: <strong>{{ player.treatment_group }}</strong></p>
{{ next_button }}
{{ endblock }}
#2
by
BonnEconLab
`def creating_session` has to be at the top level, not in class Subsession.
The following should work:
def creating_session(subsession):
for player in subsession.get_players():
player.treatment_group = random.choice(['A', 'B'])
#3
by
BonnEconLab
(edited )
Please be aware, however, that player fields have a lifetime of a single period (= subsession) only. Hence, if you have multiple rounds that code will re-randomize the treatment in every single round.
If you want the assignment to the treatments to remain constant across rounds, you have to add a condition `if subsession.round_number == 1`:
def creating_session(subsession):
#import random # If not imported globally
for player in subsession.get_players():
if subsession.round_number == 1:
player.treatment_group = random.choice(['A', 'B'])
else:
player.treatment_group = player.in_round(subsession.round_number - 1).treatment_group
Alternatively, you can use a participant field instead of a player field, as explained on
https://otree.readthedocs.io/en/latest/treatments.html#treatment-groups-multiple-rounds.
#4 by Riley
Oh, I see thank you very much. I only need the randomization in the beginning of the session as there is only one round. I think this should work. Thanks a lot this helped me!