I'm trying to generate a random array of numbers. There are x rounds in my experiment. I want that a different picture is displayed in each round and that the pictures appear in a random order.
I'm trying to embed some python code in models.py
in order to do that but I'm not getting anywhere.
Asked
Active
Viewed 1,055 times
1

IonicSolutions
- 2,559
- 1
- 18
- 31

TEC
- 53
- 7
1 Answers
1
ok, let's say you have a set of images named 'img1.jpg, img2.jpg, img3.jpg' and so on - and for the simplicity let's assume that the number of such images coincides with your number of rounds.
a bit naïve but workable way of doing this is the following:
in models.py
:
import random
class Constants(BaseConstants):
imgs = ['img1.jpg', 'img2.jpg', 'img3.jpg',]
class Subsession(BaseSubsession):
def creating_session(self):
if self.round_number == 1:
for p in self.session.get_participants():
imgs = Constants.imgs.copy()
random.shuffle(imgs)
p.vars['images'] = imgs
in pages.py
:
class MyPage(Page):
def vars_for_template(self):
image = self.participant.vars['images'][self.round_number - 1]
return {'img_to_show': image}
that's it: you have an individual randomized image to show in each round for each participant, which you can later on use on a template for this page
PS: I called this approach naive because a slightly more sophisticated way of doing it would be to access the folder where the images are stored and get a subset of them that corresponds to the number of rounds in a game. But sometimes this direct approach is more error-prone.

Philipp Chapkovski
- 1,949
- 3
- 22
- 43
-
Thanks, that seems to work! But how would I embed this in the template/html? Specifically, how do I call the image. Usually I just source it from the template folder in my computer, but in this case I'm not really sure. – TEC Jun 05 '18 at 00:11
-
Create a `static` folder in your app folder and put your images there. Then on a template where you pass `img_to_show` use: `
` – Philipp Chapkovski Jun 05 '18 at 06:13
-
Thank you so much! – TEC Jun 05 '18 at 17:24